const assertions are super handy

It turns out that const assertions are super handy to simplify typing. Code below uses const assertion on an object literal and, in fact, it compiles:

const s = {
  1: "foo",
  2: "bar",
} as const

function fn(s: "foo" | "bar") {}

fn(s[1])

Without the assertion, the type of s[1] is string, and string is not assignable to 'foo' | 'bar'. Deeper dive here.


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