2017-08-23 57 views
0

爲什麼對象的constructor字段沒有構造體簽名?Typescript:構造函數字段缺少構造體簽名

class X { 
} 

const x = new X 
// disallowed: 
// const y = new x.constructor 
// cast to any just to see runtime behaviour: 
const z = new (x.constructor as any) 
console.log(z) 

毫無疑問,有一個非常好的類型相關的原因,但我不明白它是什麼。

回答

1

這是因爲所有Object S的constructor propertyFunction

interface Object { 
    /** The initial value of Object.prototype.constructor is the standard built-in Object constructor. */ 
    constructor: Function; 
    ... 
} 

所以,你要投它,但你可以把它轉換爲更有意義比any

type XConstructor = { 
    new(): X; 
} 
const z = new (x.constructor as XConstructor) 
1

有現有的GitHub issue關於此;你可以閱讀那裏的討論爲什麼這還沒有完成。它的主旨似乎是它使typing subclasses difficult,因爲子類的構造函數不必是基類的構造函數的子類型。

如果你不關心的子類,你可以控制類的聲明(或合併到它),你可以在每個階級基礎做自己:

class X { 
    ['constructor']: typeof X; 
}  
const x = new X; 
const z = new x.constructor() // okay now 

或只是做鑄造正如@ NitzanTomer的回答中所提到的。

祝你好運!