簡體   English   中英

是否可以在打字稿中使用泛型重用重載類型

[英]Is it possible to reuse overloading type with generic in 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 -> 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?
}

您可以根據傳入的泛型定義條件類型

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

操場

您可以使用其他答案建議的條件類型。 但是更簡單的方法是使用接口在字符串和類型之間進行映射並使用類型查詢

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM