是否可以在打字稿中使用泛型重用重载类型

时间:2019-04-13 02:31:00

标签: typescript typescript-typings

我了解这个问题可能不清楚。请阅读以下示例。

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 -> TypeASchemas.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?
}

2 个答案:

答案 0 :(得分:0)

您可以根据传入的泛型定义条件类型

type RetType<T extends Schemas> = T extends Schemas.TypeA ? ResultForA : ResultForB<TypeB>;

playground

答案 1 :(得分:0)

您可以使用其他答案建议的条件类型。但是更简单的方法是使用接口在字符串和类型之间进行映射并使用类型查询

type TypeA = {
    foo: string
}

type TypeB = {
    bar: string
}
interface Schemas {
    TypeA: TypeA,
    TypeB: TypeB,
}

type Result<T> = {
    error: string,
    value: null
} | {
    error: null,
    value: T
}


function checkType<K extends keyof Schemas>(schema: K, value: any): Result<Schemas[K]> {
    return null!;

}

checkType("TypeA", null)
相关问题