TypeScript | Array of Numbers as Type

(Last edited: November 19, 2019)

const odd = [1, 3, 5, 7, 9] as const
const even = [0, 2, 4, 6, 8] as const

// 1 | 3 | 5 | 7 | 9 | 0 | 2 | 4 | 6 | 8
type SingleDigitNumber = (typeof odd | typeof even)[number]

const allNumbers = [odd, even]
// 1 | 3 | 5 | 7 | 9 | 0 | 2 | 4 | 6 | 8
type SingleDigitNumber2 = typeof allNumbers[number][number]

Using Arr[number] will get the contents of an array as a union.

For arrays of arrays, unwrap the array contents as much needed.

Playground example.


© 2022, built with Gatsby. Subscribe via RSS.
Crafted by John Darryl Pelingo
. All rights reserved.