Why is object.constructor a “Function”, and not “newable” in TypeScript?

前端 未结 1 1166
醉酒成梦
醉酒成梦 2021-01-24 12:29

In TypeScript, I usually define the type of a class type with:

declare type Type = { 
    new (...args: any[]): any
}

For example, this can use

相关标签:
1条回答
  • 2021-01-24 12:46

    Because TypeScript currently has no special handling for the constructor property. It's defined in lib.d.ts for the Object interface, so it can only be generically defined as a Function.

    https://github.com/Microsoft/TypeScript/issues/3841 and https://github.com/Microsoft/TypeScript/issues/4356 are the relevant issues.

    You can do this:

    class Foo {
        constructor(public x: string) { }
    }
    var foo = new Foo("foo");
    
    var bar = new (foo.constructor as { new(x: string): typeof foo })("bar");
    

    which allows you to be generic on the type of foo (i.e. you don't need to explicitly write Foo in the type assertion), but you still need to write the parameters explicitly or cop out with ...args: any[].

    0 讨论(0)
提交回复
热议问题