我正在为我的图书馆制作打字稿界面。这是我的目录结构:
.
├── app.js
├── index.js
├── package.json
└── typings
├── index.d.ts
├── test.js
├── test.ts
└── tsconfig.json
每个文件的内容:
index.js:
const Store = function(number) {
if (!this) {
throw new Error('You need to instantiate using the "new" keyword');
}
if (typeof (number) !== 'number') {
throw new Error('Invalid number');
}
this.number = number;
this.get = () => {
return this.number;
};
this.set = (newNumber) => {
if (typeof (newNumber) !== 'number') {
throw new Error('Invalid number');
}
this.number = newNumber;
};
}
module.exports = Store;
app.js:
const Store = require("./index");
const N = new Store(5);
console.log(N.get());
N.set(9);
console.log(N.get());
类型/index.d.ts:
export default class Store {
constructor(number: number);
get(): number;
set(newNumber: number): void;
}
类型/test.ts:
import Store from "../";
const N = new Store(5);
console.log(N.get());
N.set(9);
console.log(N.get());
类型/tsconfig.json:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"lib": ["es6", "dom"],
"noEmit": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noImplicitThis": true,
"baseUrl": "../",
"typeRoots": ["./"],
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true
}
}
要测试我的库,我用下一条命令编译了test.ts:
tsc test.ts
输出为test.js并具有以下内容:
"use strict";
exports.__esModule = true;
var __1 = require("../");
var N = new __1["default"](5);
console.log(N.get());
N.set(9);
console.log(N.get());
当我使用node执行test.js时,出现以下错误:
var N = new __1["default"](5);
^
TypeError: __1.default is not a constructor
at Object.<anonymous> (/home/alexander/Escritorio/typeTest/typings/test.js:4:9)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
如果我更改此行:
var N = new __1["default"](5);
为此:
var N = new __1(5);
代码成功执行。
app.js正确执行,其输出为:
5
9
我试图发布该程序包并再次对其进行测试,但仍然出现相同的错误。