Home > Back-end >  TypeScript: Convert array of strings to its elements
TypeScript: Convert array of strings to its elements

Time:05-04

Say I have an array const arr = ['key1', 'key2', 'key3']. How do I make a type like

type Test = { str: Items<arr> }

so that Test types have a str attribute that is either 'key1', 'key2', 'key3'?

CodePudding user response:

By default TypeScript will infer arr type as string[]. If we want to infer it as ['key1', 'key2', 'key3'] we can either do as const or as ['key1', 'key2', 'key3']

To get union type of object values you need to pass a union of object indices as a type index. type ValueOf<T> = T[keyof T]. But in this case we have an array so just [number] will do.

const arr = ['key1', 'key2', 'key3'] as const;

type Test = { str: typeof arr[number] }

const test: Test = {
  str: 'key1'
}

TypeScript playground link

CodePudding user response:

Define a type for just the values of str property separately. Then use it when defining your custom type Type.

Something like the following:

type Str = 'key1' | 'key2' | 'key3';
type Type = { str: Str }
  • Related