2017-08-23 14 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秒の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の答えで述べたように。

幸運を祈る!

関連する問題