Want a faster signal before interviews? Take the Interview Ready Check →

DAY 12 OF 30

as const

Yesterday, in one sentence

What is a literal type in TypeScript?

Interview question

What is a literal union, and why would you use one instead of string?

Type inferenceType Inference sets a different type depending on whether a value can be reassigned.

let hero = "xavier"; // inferred as string
const villain = "magneto"; // inferred as "magneto"

hero is a let and so can be reassigned later, which is why TypeScript infers string. villain is a const and so cannot be reassigned, which is why TypeScript infers the literal typeLiteral Type "magneto".

When you assign a const to an object or an array, the values inside can still be reassigned, so TypeScript does not infer a literal type for them.

const jean = { side: "hero" }; // { side: string }
const powers = ["telepathy", "telekinesis"]; // string[]

as const tells TypeScript to infer the narrowest type it can and make everything readonly. It applies all the way down, so nested object properties and array values are inferred as their literal types and made readonly as well.

const jean = { side: "hero" } as const; // { readonly side: "hero" }

jean.side = "villain"; // ❌ Cannot assign to 'side', it is read-only

It does the same to an array, which also becomes a tuple typeTuple with a fixed length.

const powers = ["telepathy", "telekinesis"] as const;
// readonly ["telepathy", "telekinesis"]

powers[0] = "flight"; // ❌ Cannot assign to '0', it is read-only

Check yourself

What type is inferred for roster?
const roster = ["Scott", "Jean"] as const
What does as const do in TypeScript?