abc
abc

Reputation: 1559

TypeScript: Convert array of strings to its elements

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

Upvotes: 2

Views: 438

Answers (2)

Obum
Obum

Reputation: 1633

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 }

Upvotes: 1

Temoncher
Temoncher

Reputation: 704

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

Upvotes: 2

Related Questions