Union type from an array of strings

1 min read

Sometimes typescript can feel like duplication, describing code that is already static (constant). Heres one trick to mitigate that by generating a string literal union type from an array.

// *as const* tells typescript that this array won't change
const intervals = ["hour", "day", "week", "month", "year"] as const

// *typeof* grabs all of the values with a *number* index and creates a union type
type Intervals = typeof intervals[number]

The resulting type, if it was hard-coded would become a union type of string literals.

type Intervals = "hour" | "day" | "week" | "month" | "year"

const assertions (as const) were introduced in Typescript 3.4. If you are using babel to transform your typescript code, make sure that your @babel/preset-typescript and @babel/core packages are up to date.

Was this article helpful?