checking against a string literal type at runtime

String literal types are not available at runtime, so how if one needs to check against them at runtime? It turns out this is possible with const assertions:

const Fruits = ["Apple", "Banana"] as const
type Fruit = typeof Fruits[number]
const isFruit = (s: String) => Fruits.includes(s as Fruit)

Deeper dive here.


Would you like to connect? Subscribe via email or RSS , or follow me on Twitter!