Typescript 如何从 class 构造函数参数推断类型
Typescript how to infer type from class constructor arguments
我有一个 class 定义,它在构造函数中输入了参数。我想在别处重用参数类型定义而不重构或从 class 中提取定义。我怎样才能做到这一点。下面是一个 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'
};
TypeScript 为此包含一个实用程序类型:ConstructorParameters<Type>
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'
};
我有一个 class 定义,它在构造函数中输入了参数。我想在别处重用参数类型定义而不重构或从 class 中提取定义。我怎样才能做到这一点。下面是一个 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'
};
TypeScript 为此包含一个实用程序类型:ConstructorParameters<Type>
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'
};