As shown elsewhere (e.g. TypeScript String Union to String Array) it is easy to define union type from tuple:
const arr = ["foo", "bar"] as const
const Item = typeof arr[number]
Unfortunately I cannot use arr
where Item[]
is required - the type of arr
is readonly ["foo", "bar"]
, and even direct type cast results in typescript error TS2352.
Typescripts suggests to cast to unknown
first - it works but it looks confusing and kind of defeats the whole purpose of type-safe array constant:
const _arr: Item[] = (arr as unknown) as Item[]
Is there any better way to have both the full list of options as Item[]
and Item
union type without repeating the actual options, other than above double cast?