2

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
Biswa
  • 23
  • 3
  • You did not mention what is your problem. – Raju Ahmed Oct 31 '21 at 08:22
  • I need to set the typescript type of the values array so that it can only accept values that are only available in the frequencyOptions array. – Biswa Oct 31 '21 at 08:25
  • Do you control options array creation? `frequencyOptions` – Aleksey L. Oct 31 '21 at 08:25
  • 1
    @AlekseyL. Yes, the `frequencyOptions` array will be mostly constant/static – Biswa Oct 31 '21 at 08:26
  • Does this answer your question? [TypeScript: Define a union type from an array of strings](https://stackoverflow.com/questions/52085454/typescript-define-a-union-type-from-an-array-of-strings) – Tino Oct 31 '21 at 08:37

1 Answers1

3

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.

Aleksey L.
  • 35,047
  • 10
  • 74
  • 84