typescript - 是否可以在打字稿中重用具有泛型的重载类型
问题描述
我知道这个问题可能不清楚。请阅读以下示例。
type TypeA = {
foo: string
}
type TypeB = {
bar: string
}
enum Schemas {
TypeA = "TypeA",
TypeB = "TypeB",
}
type Result<T> = {
error: string,
value: null
} | {
error: null,
value: T
}
function checkType(schema: Schemas.TypeA, value: any): Result<TypeA>
function checkType(schema: Schemas.TypeB, value: any): Result<TypeB>
function checkType(schema: Schemas, value: any): Result<any> {
// Some check
}
您可以为具有特定输入的函数创建重载。但是,是否可以重用关系Schemas.TypeA -> TypeA
和Schemas.TypeB -> TypeB
其他函数但使用泛型?
function checkType2<T extends Schemas>(schema: T, value: any): Result<any> {
// How to write the return type to achieve same result with overloading?
// With Some kind of keyof from a mapping object?
}
解决方案
您可以根据传入的泛型定义条件类型
type RetType<T extends Schemas> = T extends Schemas.TypeA ? ResultForA : ResultForB<TypeB>;
推荐阅读
- dialogflow-es - DialogFlow FulfillmentText 未出现在聊天默认响应中
- java - Gradle 文件内容为灰色
- facebook - Facebook 的“游戏”只是生成的图像——它们是如何完成的?
- postgresql - 无法执行 uuid_generate_v5
- sql - 显示 case_num 列的实例 > 1 的所有列,并按每个 case_num 的数量 desc 排序
- powershell - Powershell:将上次修改时间与特定日期进行比较并替换为正确的日期
- javascript - 将 C# 列表转换为 javascript 数组
- java - 重试队列绑定到 RabbitMQ 交换
- ios - Swift - 从模态视图访问 UIImagePickerController
- python - 原子或可视代码均未显示数据集输出