簡體   English   中英

Typescript generics,使用泛型字段作為映射類型

[英]Typescript generics, use field of generic as mapped type

可怕的標題,我知道。 我不知道如何簡明扼要地描述這一點。

我正在嘗試制作一個 function 對象數組,每個對象都有一個“類型”字段,以及一組處理各種類型的函數。

下面的代碼是我正在做的嘗試:

您可以在對處理程序的調用中看到我試圖描述的 object。

type Foo = {type: "foo", name: string}
type Bar = {type: "bar", score: number}

type Props<T extends {type: string}> = {
  variables: T[];
  functions: {
    [k in T["type"]]: (args: T) => void;
  }
}

function handler<T extends {type: string}>({variables, functions}: Props<T>) {
  variables.forEach(v => {
    functions[v.type](v); 
    // ^^^^^^^^^^^^^
    // No index signature with a parameter of type 'string' was found on type '{ [k in T["type"]]: (args: T) => void; }'.
  })
}

handler({
  variables: [{type: "foo", name: ""}, {type: "bar", score: 0}],
  functions: {
    "foo": (args) => {args.name}, // <--- args has type Foo | Bar, ideally would just be Foo
    "bar": (args) => {args.score},
  }
})

我不確定我哪里出錯了,任何幫助將不勝感激。

您可以在 Props 類型定義中將鍵設置為字符串

type Props<T extends {type: string}> = {
  variables: T[];
  functions: {
    [k in T["type"] as string]: (args: T) => void;
  }
}

但是,您注意到您沒有在代碼中使用 Foo 和 Bar 類型。 如下使用它們會引發錯誤,表明您的設計中有問題。

type Foo = {type: "foo", name: string}
type Bar = {type: "bar", score: number}

type Props<T extends {type: string}> = {
  variables: T[];
  functions: {
    [k in T["type"] as string]: (args: T) => void;
  }
}

function handler<T extends {type: string}>({variables, functions}: Props<T>) {
  variables.forEach(v => {
    functions[v.type](v); 
    
  })
}

handler<Foo | Bar>({
  variables: [{type: "foo", name: ""}, {type: "bar", score: 0}],
  functions: {
    "foo": (args:Foo) => {args.name}, // <--- error here as name is not in Bar
    "bar": (args:Bar) => {args.score}, // <--- error here as name is not in Foo
  }
})

我建議改變你對道具的定義

暫無
暫無

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

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