简体   繁体   中英

Is it possible to reuse overloading type with generic in typescript

I understand that the question may not be clear. Please read the following example.

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
}

You can the create overloads for function with specific input. However, is it possible to reuse the relation Schemas.TypeA -> TypeA and Schemas.TypeB -> TypeB in other functions but using generics?

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

you can define conditional type based on incoming generics

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

playground

You could use a conditional type as suggested by another answer. But a simpler approach would be to use an interface to map between strings and types and use a type query

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM