首页 > 解决方案 > 是否可以在打字稿中重用具有泛型的重载类型

问题描述

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

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

标签: typescripttypescript-typings

解决方案


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

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

操场


推荐阅读