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
5
  • You did not mention what is your problem. Commented Oct 31, 2021 at 8: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. Commented Oct 31, 2021 at 8:25
  • Do you control options array creation? frequencyOptions Commented Oct 31, 2021 at 8:25
  • 1
    @AlekseyL. Yes, the frequencyOptions array will be mostly constant/static Commented Oct 31, 2021 at 8:26
  • Does this answer your question? TypeScript: Define a union type from an array of strings Commented Oct 31, 2021 at 8:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.