Typescript使用条件类型推断构造函数参数
与通过类型推断使用Typescript推断函数参数的方式类似:Typescript使用条件类型推断构造函数参数,typescript,types,type-inference,Typescript,Types,Type Inference,与通过类型推断使用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&
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 FunctionProps=T扩展(arg1:inferu)=>any?U:从来没有;
常量stringFunc:(str:string)=>string=(str:string):string=>str;
类型StringFuncType=FunctionProps;
常量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'
类型ConstructorProps=T扩展{
新的(arg1:推断U):T;
} ? U:从来没有;
类Foo{构造函数(a:string){}
类型FooConstructor=ConstructorProps;
//FooConstructor始终为never,但应为string类型。
常量a:FooConstructor='a'
我不确定Typescript是否支持这一点,因为TS文档中的“高级类型”部分只提到函数,而没有提到用于推断的类(关于参数)
其他人找到了解决方案吗?如果我将构造函数的返回类型中的
T
更改为any
,则示例有效:
type ConstructorProps<T> = T extends {
new (arg1: infer U): any;
// ^^^
} ? U : never;
类型ConstructorProps=T扩展{
新(arg1:推断U):任何;
// ^^^
} ? U:从来没有;
请记住,T
是构造函数的类型,它与构造对象的类型不同。类测试{
class Test {
constructor(foo: number, baz: string) {}
}
type FirstConstructorProp<T> = T extends {
new (first: infer U, ...rest: any[]): any;
} ? U : never;
type F1 = FirstConstructorProp<Test>; // never
type F2 = FirstConstructorProp<typeof Test>; // number
type ConstructorProps<T> = T extends {
new (...args: infer U): any;
} ? U : never;
type P1 = ConstructorProps<Test>; // never
type P2 = ConstructorProps<typeof Test>; // [number, string]
构造函数(foo:number,baz:string){}
}
类型FirstConstructorProp=T扩展{
新的(第一个:推断U,…其余:任意[):任意;
} ? U:从来没有;
F1类型=FirstConstructorProp;//从未
类型F2=FirstConstructorProp;//数
类型ConstructorProps=T扩展{
新(…参数:推断U):任何;
} ? U:从来没有;
类型P1=构造函数Props;//从未
类型P2=构造函数Props;//[数字,字符串]
如果不使用花括号,则可以使用,请参见另一个
type ConstructorArgs=T扩展了new(…args:inferu)=>any?U:从来没有;
福班{
构造函数(foo:string,bar:number){}
}
类型栏=构造函数args//type栏=[字符串,数字]
请参阅相关的这不起作用。它总是推断永远不会。我使用的是typescript v3.5.3。请提供一个typescript示例,这里是它不起作用的证明。