类似于如何通过类型推断使用Typescript推断函数参数:
type FunctionProps<T> = T extends (arg1: infer U) => any ? U : never;
const stringFunc: (str: string) => string = (str: string): string => str;
type StringFuncType = FunctionProps<typeof stringFunc>;
const a: StringFuncType = 'a';
我想以相同的方式推断构造函数参数,但到目前为止还没有成功。目前我的设置如下:
type ConstructorProps<T> = T extends {
new (arg1: infer U): T;
} ? U : never;
class Foo { constructor(a: string) { } }
type FooConstructor = ConstructorProps<typeof Foo>;
// FooConstructor is always never but should be type string.
const a: FooConstructor = 'a'
不确定在Typescript中是否支持这一点,因为TS文档中的“高级类型”部分仅提及函数而不是推理类(关于参数)。
还有其他人找到解决方案吗?
如果我在构造函数的返回类型中将T
更改为any
,则该示例有效:
type ConstructorProps<T> = T extends {
new (arg1: infer U): any;
// ^^^
} ? U : never;
请记住,T
是构造函数的类型,它与构造对象的类型不同。