如何在TypeScript中键入作为对象属性的构造函数?

如何在TypeScript中键入作为对象属性的构造函数?,typescript,Typescript,我有一个属性为构造函数的对象。如何正确键入此内容: interface MyObj { constructor: () => ({ init: () => void }) } const myObj = { constructor: function(this: any) { this.init = function() { this.var = 5; } } } 这是没有错误的,但这是因为我在构造函

我有一个属性为构造函数的对象。如何正确键入此内容:

interface MyObj {
    constructor: () => ({ init: () => void })
}

const myObj = {
    constructor: function(this: any) {
        this.init = function() {
            this.var = 5;
        }
    }
}
这是没有错误的,但这是因为我在构造函数中有
This:any
。如果我删除了,我就有错误了

类型“{constructor:()=>void;}”上不存在属性“init”

类型“{constructor:()=>void;}”上不存在属性“var”


像这样键入构造函数的正确方法是什么?

您应该使用关键字“new”来描述构造函数的类型

见下例:

首先,我们定义构造函数选项接口

interface MyObjConfig<T> {
    init: (instance: T) => void;
}
interface MyObj<T> {
    constructor: new (config: MyObjConfig<T>) => T;
}
class MyObjItem {
    public var: number;
}

const myObj: MyObj<MyObjItem> = {
    constructor: MyObjItem
};
const initiator = (instance: MyObjItem) => {
    instance.var = 5;
};


const concreteInstance = new myObj.constructor({ init: initiator });