Lesson 8
20 min
type, &, enum, as const and type assertions: name and combine your types.
Definition
A type alias is a name you give to a type so you can reuse it. An intersection combines several types into a single one that has all of their properties. Anenum is a set of named constants. These three tools are used to describe precise, readable and reusable types.
So far, you have used types as they are, one at a time. In a real project, the same types come up everywhere, sometimes combined, sometimes limited to a few values. This lesson presents the tools that let you name them, assemble them and protect them against modification.
A type alias gives a name to any type, not just an object. It makes the code more readable and avoids repeating complex types.
type Identifier = string | number;
type Coordinates = [number, number];
type Callback = (message: string) => void;
let userId: Identifier = "ABC-1";
let position: Coordinates = [48.85, 2.35];
const notify: Callback = (msg) => console.log(msg);
An alias doesn't create a new type: it only gives a second name to an existing type. So a value of type Identifier is still simply a string or a number. By convention, an alias name starts with a capital letter.
type Product = {
id: Identifier;
name: string;
price: number;
};
type Cart = Product[];
const myCart: Cart = [
{ id: 1, name: "Notebook", price: 3.5 },
{ id: "P-2", name: "Pen", price: 1.2 },
];Where a union says "one or the other", an intersection, written &, says "one and the other": the resulting type has all the properties of the combined types.
type Identity = {
name: string;
age: number;
};
type Contact = {
email: string;
phone?: string;
};
type Customer = Identity & Contact;
const customer: Customer = {
name: "Lea",
age: 25,
email: "lea@example.com",
};The intersection is very useful for composing types from small pieces: you write Identity once, Contact once, then assemble them as needed. If an object of type Customer forgets a required property, such as email, TypeScript reports it right away.
Warning
If two types combined by intersection declare the same property with incompatible types (for example id: string on one side and id: number on the other), the type of that property becomes never and the object becomes impossible to build.
Intersection also works with interfaces, and you can mix the two notations. It is an alternative to extends: instead of inheriting from an interface, you assemble existing types. In both cases, the result requires all the properties.
interface Timestamped {
createdAt: Date;
}
type Comment = {
author: string;
text: string;
};
type DatedComment = Comment & Timestamped;
const c1: DatedComment = {
author: "Tom",
text: "Very clear!",
createdAt: new Date(),
};An enum defines a set of named constants. By default, the values are numbered starting at 0, but you can assign text to them, which is more readable when you display or store the value.
enum Direction {
Up,
Down,
Left,
Right,
}
enum Role {
Admin = "ADMIN",
Editor = "EDITOR",
Reader = "READER",
}
let heading: Direction = Direction.Left;
const myRole: Role = Role.Admin;
console.log(heading); // 2
console.log(myRole); // "ADMIN"You can also choose the numbers yourself by specifying the first value: the following ones are then numbered in sequence. With Level.Medium = 5, for example, the next level would be 6. Text enums are generally preferable, because their value is understandable when you read it in a database or in an API response.
enum Level {
Beginner = 1,
Medium, // 2
Expert, // 3
}
function describe(n: Level): string {
return "Level number " + n;
}A text enum also exists at runtime: it is a real JavaScript object. You can therefore loop over it, for example to fill a dropdown list, with Object.values. The resulting array is correctly typed.
enum Role {
Admin = "ADMIN",
Editor = "EDITOR",
Reader = "READER",
}
const allRoles = Object.values(Role); // Role[]
for (const r of allRoles) {
console.log(r); // ADMIN, EDITOR, READER
}An enum generates JavaScript code at runtime, whereas a literal union disappears completely at compilation. Many developers therefore prefer unions, which are lighter and very readable:
type RoleUnion = "admin" | "editor" | "reader";
function authorize(role: RoleUnion): boolean {
return role === "admin";
}
authorize("admin"); // OK
authorize("guest"); // ErrorGood to know
Both approaches are valid. If you work in an existing project, follow the convention already in place rather than mixing styles.
In this example, the authorize function rejects "guest" as soon as the code is written, just as an enum would, but without generating a single line of JavaScript. For a simple list of allowed values, it is often the most economical choice.
Adding as const to a literal asks TypeScript to treat it as entirely frozen: properties become read-only and values keep their precise literal type. It is used to derive a type from a list of values.
const COLORS = ["red", "green", "blue"] as const;
type Color = (typeof COLORS)[number]; // "red" | "green" | "blue"
let choice: Color = "green"; // OK
choice = "yellow"; // Error
The advantage of this technique is that there is only one source of truth: the list of values. You can loop over it or display it in a menu, and the Color type updates itself if you add a color to the array.
Before moving on to assertions, keep this general principle in mind: the more precise a type is, the more TypeScript can help you. Aliases, intersections, enums and as const all go in that direction, whereas assertions are only for taking control when the compiler can't guess.
Sometimes, you know more than TypeScript about the type of a value. The as keyword lets you impose a type on it. Be careful: you then have no protection at all, because TypeScript trusts you without checking.
const element = document.getElementById("name") as HTMLInputElement;
console.log(element.value);
// Dangerous: if the element doesn't exist, the program will crash
// Prefer an explicit check when possibleThe satisfies operator is a safer alternative: it checks that a value respects a type without widening the inferred type.
type Palette = Record<string, string | number[]>;
const theme = {
primary: "#3b82f6",
secondary: [255, 0, 128],
} satisfies Palette;
theme.primary.toUpperCase(); // OK: TypeScript knows it's a string
theme.secondary.map((n) => n); // OK: it really is an arrayThe Record<string, ...> type describes an object whose keys are all texts and whose values all have the indicated type. Without satisfies, annotating theme: Palette would have erased the distinction between text and array, and both method calls above would have been rejected.
A special case of assertion is the exclamation mark placed after a value. It tells TypeScript that the value is neither null nor undefined. Like any assertion, it removes the check: if you are wrong, the program will crash at runtime.
const button = document.querySelector<HTMLButtonElement>("#send");
// button.click(); // Error: button may be null
button!.click(); // Accepted, but risky
// Safe version
if (button) {
button.click();
}type Euro = number is still an ordinary number.satisfies.To practice, try spotting the types that repeat in your own projects: they are the best candidates to become aliases, and values repeated as text are good candidates to become literal unions.
&) combines the properties of several types.as const freezes a value and lets you derive a precise type from it.as imposes a type without checking; satisfies checks without widening.Exercise
Status enum (Draft, Published, Archived) and aPost type with a title and a status. Then write a function that displays a different message depending on the status.Going further
as const array of sizes ("S","M", "L"), derive a Size type, then combine it with a Product interface by intersection.