Typescript使用条件类型推断构造函数参数

问题描述 投票:0回答:1

类似于如何通过类型推断使用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文档中的“高级类型”部分仅提及函数而不是推理类(关于参数)。

还有其他人找到解决方案吗?

typescript types type-inference
1个回答
3
投票

如果我在构造函数的返回类型中将T更改为any,则该示例有效:

type ConstructorProps<T> = T extends {
  new (arg1: infer U): any;
//                     ^^^
} ? U : never;

请记住,T是构造函数的类型,它与构造对象的类型不同。

© www.soinside.com 2019 - 2024. All rights reserved.