typescript - 如何在打字稿中使用通用返回值注释函数
问题描述
给定一个返回工厂的函数,我如何注释函数/工厂以使其包含正确的类型定义?
这是我的例子:
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中在剩余参数和展开表达式中使用元组,并将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');
推荐阅读
- angular - 从 API 为其他模块保存数据
- mysql - 谁能告诉我如何在数据库中逐行查找总和
- python - Python:使用 TensorFlow 计算神经网络的准确度
- vue.js - 如何确定 Web 应用程序是在开发模式还是生产模式下运行?
- amazon-web-services - AWS CloudFormation 模板 EC2 – 根据 VPC 选择返回子网列表
- html - 我怎样才能让这个动画“铁路文本”在例子中看到
- nativescript - RadListView 与两个滚动(水平和垂直)
- spring-boot - 我的 @WebMvcTest 测试类如何在 Spring Boot 中使用此 JDBC 身份验证配置进行初始化?
- azure-devops - 如何使用 REST API 在发布定义中设置代理队列?
- excel - 使用 VBA,通过引用该范围复制格式为 12.3456 的范围会得到 12,3456。(用逗号代替点)