如何在打字稿中用通用返回值注释函数

2024-04-24

给定一个返回工厂的函数,如何注释该函数/工厂以使其包含正确的类型定义?

这是我的例子:

class item<T> {
  constructor(a: T) {
    this.a = a;
  }
  a: T
}

function generate(c) {
  return function a(a) {
    return new c(a);
  }
}

const factory = generate(item); // I want this to always be annotated as <T> (a: T) => item<T>

const instance = factory('string'); // instance should now be of type item<string>

这在打字稿中可能吗?或者我应该建议它作为一个新功能?


对于非泛型类,我们可以在 3.0 中使用剩余参数和扩展表达式中的元组 https://github.com/Microsoft/TypeScript/pull/24897 and InstanceType将构造函数映射到类似的函数。

不幸的是,对于泛型类,映射时无法保留类型参数。唯一的解决方案是向类添加一个字段来告诉generate结果类型应该是什么。这可以使用接口类合并来完成,这样原始类就不知道生成。

使用这两种方法(可能时自动,必要时手动)的可能解决方案可能如下所示:

class item<T> {
    constructor(a: T) {
        this.a = a;
    }
    a: T
}

const generateResult = Symbol.for("generate")
interface item<T> {
    [generateResult] : <T>(a: T) => item<T>    
}

type d = item<any>[typeof generateResult]

type SupportsGeneration<R> =  { [generateResult] : R }
type ConstructorArguments<T> = T extends new (...a:infer A ) => any ? A : [];


function generate<T extends { new (...a:any[]) : SupportsGeneration<any> }>(c:T) :  InstanceType<T> extends SupportsGeneration<infer R> ? R: never
function generate<T extends new (...a:any[]) => any>(c:T) :  (a: ConstructorArguments<T>) => InstanceType<T>
function generate(c: new (...a: any[]) => any) : any {
    return function a(...a: any[]) {
        return new c(...a);
    }
}

const factory = generate(item); 

const instance = factory('string');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在打字稿中用通用返回值注释函数 的相关文章

随机推荐