1

So I have

    typedef Choices = 'choice1' | 'choice2' |  'choice3' | 'choice4' ...
    
    const choices: Choices[] = ['choice1', 'choice2', 'choice3', 'choice3', 'choice4' ...];

Is there a more elegant way of spreading out all the Choices into an array (and object keys for that matter)?

I'd like to say something like

    const choices: Choices[] = [ ...Choices ];

So that the code adapts if additional strings are added

1
  • This can't be done with pure TS, see linked q/a above. What you can do is start with an array and generate your type from it, as the answers below and the linked q/a above mention. Commented Mar 1 at 14:12

2 Answers 2

1

Remember that you can't do stuff with types at runtime. But you could flip your thinking, and generate a type from a list:

const choices = ['choice1', 'choice2', 'choice3', 'choice3', 'choice4'] as const;

type Choices = typeof choices[number] // same as "choice1" | "choice2" | "choice3" | "choice4"
Sign up to request clarification or add additional context in comments.

Comments

0

Types are a pre transpilation construct. The actual javascript does not have types. So values can never be created from types. The other way round is possible:

const choicesArray = ['choice1', 'choice2', 'choice3', 'choice4'] as const;

type Choices = typeof choicesArray[number]
const choices: Choices[] = [...choicesArray, 'choice3'];

Playground

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.