我是TypeScript的新手,正尝试导出一个类供我的JS代码使用。
项目/测试模块/ index.ts
class Foo {
constructor(bar: number){
this.number = number;
};
bar: number;
}
项目/测试模块/ index.js
"use strict";
/// <reference path="index.ts" />
Object.defineProperty(exports, "__esModule", { value: true });
project / index.js(主文件)
const { Foo } = require('./testmodule');
console.log(new Foo(1).bar.toString());
运行中:
TypeError: Foo is not a constructor
at Object.<anonymous> (C:\Users\willi\OneDrive\Desktop\project\index.js:3:13)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
错误明显地明显吗?我不明白我在这里做错了什么。VSCode使这更加令人困惑,因为它似乎确实将Foo理解为构造函数。
这可能是编译错误:的内容index.js
未反映的内容index.ts
。请记住,对打字稿文件进行的每次更改后,都需要运行打字稿编译器,以使其反映在js输出中。如果您tsc
在监视模式下运行编译器,它将在文件更改时自动运行。
查看您的打字稿代码,甚至可能实际上是您在运行编译器,但没有注意到编译错误:您在引用的this.number
同时可能表示this.bar
。
export class Foo {
constructor(bar: number){
this.bar = bar;
};
bar: number;
}
然后您的班级可以像
import { Foo } from './testmodule';
console.log(new Foo(1).bar.toString());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句