Home > OS >  Key union from fields of mixed object array
Key union from fields of mixed object array

Time:02-25

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';

CodePudding user response:

A simpler way to get the type of a field is to index with a number typeof field[number]

You can the use the predefined Extract type to get only those constituents of the union that have a particular fieldType:

type ItemType  = typeof fields[number];

type TextItemKeys = Extract<ItemType, { fieldType: 'text'}>['id'];
type SelectItemKeys = Extract<ItemType, { fieldType: 'select'}>['id'];

Playground Link

  • Related