using an const array as a source for a string literal union

Given this:
const weatherIcons = [
'sun',
'rain',
'snow',
] as const
const weatherIcons = [
'sun',
'rain',
'snow',
] as const
How can I create a type like
type Weather = {
icon: typeof weatherIcons[number]
}
type Weather = {
icon: typeof weatherIcons[number]
}
Full example: https://www.typescriptlang.org/play/?#code/JYWwDg9gTgLgBAbzgLzgXzgMyhEcDkyEAJvgLABQoksicMAnmAKbpY574CGUA1oy3IVKAYwgA7AM7wA7sy4wAFsygBJMVLgBeOAG1KcApICu4-ABoDBKF2BnLFQ-kniIMi5QC6cLpLgbpSiCKAPhkAGURZRAubRQAOggAIwArZhEYAAoEKxhmcAAuBPFjECSVTIBKB0NgDSLkeOYSkEy5BWU1AOrKNErKAVYALUjo2J1Gu0wVAB5BiEwUUfyuAD4BpmHlmIB1eSUVdQk4kaiV3Xw6iXxPSgB6O8M4AD0AfmDRCWkfbfH6TeyuXyYCK+Ba5SgHkccCu4lB0igdgA5hY4A84DMALSYwyvPG9foUQZwACCvzi80WXF+8SmKg2LFJvz2HUOGjiZLOMQusJu90ehjeQA
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
4 Replies
ssalbdivad
ssalbdivad7mo ago
const weatherIcon = type("===", ...weatherIcons)
const weatherIcon = type("===", ...weatherIcons)
You can also inline it with a tuple expression like this:
const t = type({
icon: ["===", ...weatherIcons]
})
const t = type({
icon: ["===", ...weatherIcons]
})
though generally I'd recommend defining types like that as standalone first then referencing them in your definitions so they're more reusable.
AlexWayne
AlexWayneOP7mo ago
Nice. So the '===' just infers the type from what follows it?
ssalbdivad
ssalbdivad7mo ago
Yeah, it accepts spread args and validates at runtime that the input === one of them So it can be used for other references like symbols and objects as well if you want reference equality
AlexWayne
AlexWayneOP7mo ago
nice. Thank you.

Did you find this page helpful?