【发布时间】:2022-01-26 03:26:30
【问题描述】:
我有一个在构造函数上有类型参数的类定义。我想在其他地方重用参数类型定义,而不重构或从类中提取定义。我怎样才能做到这一点。下面是一个 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'
};
【问题讨论】:
-
这是因为您将实例类型
Bro传递给实用程序类型GetProps而不是构造函数类型。为了使这项工作只是const bp : GetProps<typeof Bro> ...typescriptlang.org/play?#code/…
标签: typescript generics types