TypeScript · Lesson 10 of 42
Type aliases and literal types
Name a type with type, restrict a value to a few exact strings or numbers with literal types, and use as const to keep literals precise.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will be able to give a type a name, and to describe values that may only be one of a short list of exact options. Together these are what turn loose strings such as "pending" into something the compiler can check.
Type aliases
A type alias gives a name to any type, using the keyword type. Naming shapes you reuse keeps code short and readable:
type Point = { x: number; y: number };
function distance(a: Point, b: Point): number {
return Math.hypot(b.x - a.x, b.y - a.y);
}
console.log(distance({ x: 0, y: 0 }, { x: 3, y: 4 }));5Aliases work for any type, not only objects:
type UserId = string;
type Score = number;
type Pair = [string, number];
const id: UserId = "u-17";
const score: Score = 88;
const entry: Pair = [id, score];
console.log(entry);[ 'u-17', 88 ]An alias is only a name. UserId and string are the same type to the compiler, so an alias gives readability, not extra safety. It also disappears when the code is compiled.
Literal types
Usually a string means "any text". A literal type means exactly one value. The type "north" allows only the string "north":
type North = "north";
const heading: North = "north";
console.log(heading);northA single literal is not very useful alone, but combining literals gives a closed set of allowed values. The | symbol means "or", and the next lesson covers it fully:
type Status = "pending" | "shipped" | "delivered";
function describe(status: Status): string {
return `Order is ${status}`;
}
console.log(describe("shipped"));Order is shippedIf someone passes a value outside the set, including a typo, the compiler refuses:
type Status = "pending" | "shipped" | "delivered";
function describe(status: Status): string {
return `Order is ${status}`;
}
describe("shiped");example.ts(7,10): error TS2345: Argument of type '"shiped"' is not assignable to parameter of type 'Status'.This is far safer than a plain string, where the typo would be accepted and the bug found in production. Number and boolean literals work the same way: type Dice = 1 | 2 | 3 | 4 | 5 | 6.
Widening: let versus const
As you saw earlier, a const keeps the exact literal, while let widens it:
let mode = "dark";
const theme = "dark";
const a: "dark" | "light" = theme;
const b: "dark" | "light" = mode;example.ts(5,7): error TS2322: Type 'string' is not assignable to type '"dark" | "light"'.theme is fine, because its type is "dark". mode is a plain string, because a let could change to any text, and so it is rejected. This surprises people when an object is built first and passed later:
type Direction = "up" | "down";
function move(direction: Direction) {
console.log("Moving", direction);
}
const request = { direction: "up" };
move(request.direction);example.ts(8,6): error TS2345: Argument of type 'string' is not assignable to parameter of type 'Direction'.The object's direction property is widened to string, because object properties can be changed. There are two fixes. Annotate the object (const request: { direction: Direction } = ...), or use as const.
as const
Putting as const after a value tells the compiler to keep it as precise as possible: properties become readonly and literals stay literal:
type Direction = "up" | "down";
function move(direction: Direction) {
console.log("Moving", direction);
}
const request = { direction: "up" } as const;
move(request.direction);
const levels = ["low", "medium", "high"] as const;
console.log(levels.length);Moving up
3An as const array becomes a readonly tuple of exact strings. That is a handy trick for building a list of allowed values once and deriving a type from it, a technique the lesson on keyof and typeof shows.
Common mistakes
Typing statuses as plain string. If only a few values are valid, say so with a union of literals.
Thinking an alias makes a new, incompatible type. type UserId = string is still just string.
Being surprised by widening. Object properties and let variables widen. Use as const or an annotation when you need the exact value.
Using as const everywhere. It makes values readonly, which may get in the way when you really do need to change them.
Exercise
Define a Weekday type with the seven day names as literals, and a function isWeekend(day: Weekday): boolean. Call it with a valid day and a misspelt one, and read the error. Then create an object { day: "Sat" }, try to pass its day property, and fix the error twice: once with an annotation and once with as const.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.