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

DAY 11 OF 30

Literal types

Yesterday, in one sentence

What is structural typing (duck typing) in TypeScript?

Interview question

type A = X & Y and interface A extends X, Y produce the same type. Why?

A literal type is a type whose only allowed value is one exact value.

type Alignment = "hero";

let side: Alignment = "hero";

side = "hero"; // ok
side = "villain"; // ❌ Type '"villain"' is not assignable to type '"hero"'

Literal types are most often used in a union typeUnion Type, listing every value something is allowed to be. This is called a literal union.

type Alignment = "hero" | "villain" | "antihero";

let side: Alignment = "hero";

side = "antihero"; // ok
side = "mutant"; // ❌ Type '"mutant"' is not assignable to type 'Alignment'

string would accept any text at all, including a typo. Alignment accepts exactly three values, and anything else is a build timeBuild Time error.

Literal types work with numbers and booleans too.

type Rank = 1 | 2 | 3;
type Recruited = true;

Check yourself

Which type alias only allows the values "hero", "villain" and "antihero"?
What is a literal type in TypeScript?