我有一個類定義,它在建構式上輸入了引數。我想在別處重用引數型別定義而不重構或從類中提取定義。我怎樣才能做到這一點。下面是一個GetProps<TBase>我被建議但實際上不起作用的型別的例子。我希望const bp定義會拋出錯誤,因為它缺少derp在建構式中定義的欄位。
type GetProps<TBase> = TBase extends new (props: infer P) => any ? P : never
class Bro {
bro: string = 'cool'
cool: string = 'lol'
constructor(props: {bro: string, cool: string, derp: string}){
this.bro = props.bro;
this.cool = props.cool;
}
}
const bp : GetProps<Bro> = {
bro: 'lol',
cool: 'wut'
};
uj5u.com熱心網友回復:
TypeScript 為此包含一個實用程式型別: ConstructorParameters<Type>
TS游樂場
const bp: ConstructorParameters<typeof Bro>[0] = {
/* ^^
Property 'derp' is missing in type '{ bro: string; cool: string; }'
but required in type '{ bro: string; cool: string; derp: string; }'.(2741) */
bro: 'lol',
cool: 'wut'
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/396646.html
