我有一個包含要在 UI 中顯示的不同欄位的欄位陣列。
const fields = [
{
id: 'textInput_1',
fieldType: 'text',
},
{
id: 'selectInput_1',
fieldType: 'select',
},
{
id: 'textInput_2',
fieldType: 'text',
},
] as const;
對于我的文本和選擇輸入處理程式,我希望它們分別接受其型別是id欄位fieldType值'text'聯合的鍵'select'。
我能夠得到這樣的所有鍵的聯合
type ArrayElement<ArrayType extends readonly unknown[]> = ArrayType extends readonly (infer ElementType)[] ? ElementType : never;
type ItemKeys = ArrayElement<typeof fields>['id']; // 'textInput_1' | 'selectInput_1' | 'textInput_2'
我想要的是動態的以下型別
type TextItemKeys = 'textInput_1' | 'textInput_2';
type SelectItemKeys = 'selectInput_1';
uj5u.com熱心網友回復:
獲取欄位型別的更簡單方法是使用數字進行索引typeof field[number]
您可以使用預定義的Extract型別來僅獲取具有特定的聯合的那些組成部分fieldType:
type ItemType = typeof fields[number];
type TextItemKeys = Extract<ItemType, { fieldType: 'text'}>['id'];
type SelectItemKeys = Extract<ItemType, { fieldType: 'select'}>['id'];
游樂場鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/433057.html
標籤:打字稿
上一篇:將模板文字用于括號表示法時出現TypeScript錯誤
下一篇:是否可以在打字稿中選擇宣告型別?
