我怀疑我在这里做错了什么,但是如果我在包含以下内容的Node应用程序中有现有文件demo.js
,
var Demo = function () {
let self = this;
self.sayGoodbye = (x) => `goodbye ${x}`;
};
module.exports = new Demo();
我会在常规js文件中使用它
const demo = require('./demo');
demo.sayGoodbye('foo');
我编写了一个名为demo.d.ts
的d.ts文件,该文件位于demo.js
旁边
export = Demo
declare class Demo {
sayGoodbye(x: string) : string
}
在新的打字稿文件run.ts
中,我写了以下内容:
const dem = require('./demo');
console.log(dem.sayGoodbye('foo'));
当我将鼠标悬停在dem
变量上(在VSCode中)时,该类型被列为any
,但没有任何类型信息。
这是我的tsconfig
{
"compilerOptions": {
"sourceMap": true, // allow sourcemap support
"strictNullChecks": true, // enable strict null checks as a best practice
"module": "commonjs", // specify module code generation,
"moduleResolution": "Node",
"target": "es2015", // specify ECMAScript target version
"allowJs": true, // allow a partial TypeScript and JavaScript codebase
"experimentalDecorators": false,
"types" : ["node"],
"baseUrl":"."
},
"include": [
"./**/*.ts",
],
"exclude": [
"node_modules"
]
}
如果有人可以解释d.ts在哪里出错或需要声明,我将不胜感激。
我将d.ts文件更改为此:
interface Demo {
sayGoodbye(x: string) : string
}
declare var demo : Demo
export = demo
我认为上一个实际上不代表文件。如果我对它的理解正确的话,初始输出将是构造函数而不是实例。 如果现在将run.js中的import语句更改为
import dem = require('./demo');
console.log(dem.sayGoodbye('foo'));
现在我得到了智能感知。不幸的是,已编译的JS现在具有以下行:
Object.defineProperty(exports, "__esModule", { value: true });
拥有此功能并不是一件容易的事,但我想知道如何删除它,但将require保留为基于非模块代码的导入。