Home > Software design >  Derive Type from Array Typescript
Derive Type from Array Typescript

Time:10-31

I have an array

const frequencyOptions = ['Daily', 'Weekly', 'Monthly'];

I need to set Typescript Type to another array that can contain values from the options array only like

let frequencyValues = ['Daily', 'Weekly'] // can be any combination of options array

CodePudding user response:

If you're controlling options array creation you can:

const frequencyOptions = ['Daily', 'Weekly', 'Monthly'] as const;
type Option = typeof frequencyOptions[number]; // "Daily" | "Weekly" | "Monthly"

let frequencyValues: Option[] = ['Daily', 'Weekly'];

// Expect error
frequencyValues = ['foo'] // Type '"foo"' is not assignable to type '"Daily" | "Weekly" | "Monthly"'.

Playground


as const prevents literal types widening to string, then we query tuple item type.

  • Related