2

I am trying to figure out how to create an Array out of a union type that I have created earlier.

Example:

type Temperature = 'cold' | 'warm' | 'hot';

// The end result of my array should look like this:
const ArrayOfTemperatures = ['cold', 'warm', 'hot'];

As seen in the example above, I would like to convert a union type into an array of those types, without allowing duplication if possible.

3
  • 1
    To be clear, your code is currently showing something that's impossible. You can't turn a union type (which is a purely compile-time constant) into a runtime value (an array with those strings in it). (You can do the opposite if the runtime value is constant, and thus known at compile time.) Are you really trying to do that, or are you trying to create a tuple type (not a runtime value) as in @caTS's link? Commented Oct 13, 2022 at 12:56
  • 1
    (Doing the opposite, in case it helps: typescriptlang.org/play?#code/…) Commented Oct 13, 2022 at 13:04
  • Shouldn't it – in theory – be possible to derive an array literal from a type union at compile time? Commented Nov 4 at 13:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.