gpt4 book ai didi

typescript - TS2351 : How to create constructor typings for `new function()` in ts

转载 作者:搜寻专家 更新时间:2023-10-30 21:36:23 24 4
gpt4 key购买 nike

我正在创建一个 npm 包,默认导出一个类。这个模块是用es3写的,但是我想提供types.ts

index.js(在我的包中)

function MyClass(p1, p2) {
// code
}

module.exports = MyClass;

好的,然后我创建了类型 index.d.ts(在我的包内,除了 index.js):

declare module 'mypackageid' {
interface MyClass {
new (div: HTMLElement, conf: any): MyClass;
}
export var MyClass: MyClass;
}

我可以很容易地在 es3 中使用这段代码并且它有效。 (在我的包裹之外,例如来自另一个包裹)

var myInstance = new MyClass()

但是如果我想从 .ts 文件中的另一个包中使用它:

import MyClass from 'mypackageid';

new MyClass(divReference, { // <-- error points to this line
onBlobPaste: e=> {
console.log(e);
},
});

Typescript 加载器拒绝编译并打印:

TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

编辑 1:

You use a commonjs default export in your .ts file, your .d.ts file specifies a member export, and your consumer is expecting an ES6 default export. In what way are you actually trying to export it? You have to pick one

我没有显式导入类型,我希望 typescript 能够自动从“index.d.ts”中自动检测类型。如果我像这样使用默认导出:

declare module 'mypackageid' {
interface MyClass {
new (div: HTMLElement, conf: any): MyClass;
}
export default MyClass
}

我会在下面得到错误。错误指向符合 new

S2693: 'MyClass' only refers to a type, but is being used as a value here.

最佳答案

如果您在模块中使用 exports= 方法,从而替换模块的整个导出,则需要使用 import= 和模块系统支持这个的(例如 AMD 或 commonjs)。参见 docs

mypackageid.d.ts
declare module 'mypackageid' {
class MyClass {
constructor(div: HTMLElement, conf: any);
}
export = MyClass;
}


//Usage
import MyClass = require('mypackageid')

new MyClass(null, null)

此外,如果你想使用 new 的接口(interface),那不能是导出(因为它是一种类型),你需要声明一个 const 并导出那:

declare module 'mypackageid' {
interface MyClassCtor {
new (div: HTMLElement, conf: any) : {};
}
const MyClass : MyClassCtor;
export = MyClass;
}

关于typescript - TS2351 : How to create constructor typings for `new function()` in ts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51201146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com