'Key union from fields of mixed object array
I have an array for fields containing different fields to be shown in UI.
const fields = [
{
id: 'textInput_1',
fieldType: 'text',
},
{
id: 'selectInput_1',
fieldType: 'select',
},
{
id: 'textInput_2',
fieldType: 'text',
},
] as const;
For my text and select input handlers, I want them to accept key whose type is union of values of id fields where fieldType is 'text' and 'select' respectively.
I'm able to get a union of all keys like this
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'
What I get to wish is the following types dynamically
type TextItemKeys = 'textInput_1' | 'textInput_2';
type SelectItemKeys = 'selectInput_1';
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
