0

I have an array:

const specialNumbers = [1, 10, 20, 50] as const; // type: readonly [1, 10, 20, 50]

I would like a type (ex: SpecialNumber) that is the union of the values in the arrays.

For example to be used as:

const getSpecialNumber = (): SpecialNumber => { // SpecialNumber = 1 | 10 | 20 | 50
  // ...
}

How to construct SpecialNumber from specialNumbers?

4
  • 1
    This question is similar to: Define a union type from an array of strings. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Sep 25, 2024 at 7:51
  • "[1, 10, 20, 50] as const; // type: readonly [2, 4, 6, 8]" - something is off there Commented Sep 25, 2024 at 7:57
  • @jonrsharpe, that's the answer I was looking for but it didn't appear in my search. Maybe because the question was not generic enough (the title only mention strings) Commented Sep 25, 2024 at 7:59
  • @Berg Oops good catch, I'm updating it Commented Sep 25, 2024 at 8:00

1 Answer 1

1

To get the union of the values, you can do:

type SpecialNumber = (typeof specialNumbers)[number];
Sign up to request clarification or add additional context in comments.

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.