[英]TypeScript Declaration File (Function Constructor)
I am trying to create a TypeScript Declaration file for an npm package.我正在尝试为 npm package 创建 TypeScript 声明文件。
JavaScript (index.js from npm package): JavaScript(来自 npm 包的 index.js):
function Foo(config = {}) {
this.configuration = {
prop1 = config.prop1 || 'value'
}
}
/// more...
module.exports = Foo;
My TypeScript Declaration File (index.d.ts):我的 TypeScript 声明文件(index.d.ts):
declare module '@company/modulename' {
interface config {
prop1?: string;
}
declare function Foo(config: config): void;
exports = Foo;
}
Usage (server.ts):用法(server.ts):
import { Foo } from '@company/modulename'; // <-- this fails as noted below
// const Foo = require('@company/modulename'); <-- this works!
const foo = new Foo({
prop1: 'Halp'
});
/// more stuff...
Problem:问题:
The TypeScript Declaration file is very helpful. TypeScript 声明文件非常有用。 EXCEPT, when I try to run server.ts, I get an error: TypeError: modulename_1.Foo is not a constructor
.除了,当我尝试运行 server.ts 时,我得到一个错误: TypeError: modulename_1.Foo is not a constructor
。 If I switch to the require syntax, everything works as expected... but then I don't get the type checking!如果我切换到 require 语法,一切都会按预期工作......但是我没有得到类型检查!
My tsconfig.json:我的 tsconfig.json:
{
"compilerOptions": {
"target": "ES2019",
"module": "commonjs",
"outDir": "dist",
"rootDir": "./",
/* Strict Type-Checking Options */
"strict": true,
"noImplicitAny": false,
/* Additional Checks */
/* Module Resolution Options */
"esModuleInterop": true,
/* Source Map Options */
/* Experimental Options */
/* Advanced Options */
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
UPDATED + CORRECTED:更新+更正:
My TypeScript Declaration File (index.d.ts):我的 TypeScript 声明文件(index.d.ts):
declare module '@company/modulename' {
interface config {
prop1?: string;
}
export default function Foo(config: config): void;
}
Usage (server.ts):用法(server.ts):
import Foo from '@company/modulename'; // Braces removed from Foo
const foo = new Foo({
prop1: 'Halp'
});
Does import Foo from '@company/modulename';
是否import Foo from '@company/modulename';
not work?不行? if not try, export default Foo;
如果不尝试,则export default Foo;
, then try again. ,然后再试一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.