Type Aliases and Index Signatures
Unlock the full power of type by modeling flexible value sets and dynamic object shapes that scale with your codebase.
We’ve seen how the type
keyword helps us name reusable object shapes. That was the first step—cutting down on repetition, gaining clarity, and enforcing consistency across our codebase.
But type
doesn’t stop at objects.
It can describe object shapes, value sets, and even function signatures. If it has a type, we can name it. And when we need to describe objects with unpredictable keys, TypeScript has our back there, too.
Let’s level up how we write types so our code can grow without breaking.
Modeling value sets with type aliases
Let’s say we want to annotate a value that represents a user’s access level:
type UserRole = "admin" | "editor" | "viewer";
This isn’t
This is a union type which is known as a value that can be one of several explicitly allowed options. We first met this syntax back in string | null
. Now we’re wielding it with precision—naming these unions and embedding them into real structures.
We can use union types anywhere we’d normally use a type, but they are especially useful when combined with object shapes:
type UserRole = "admin" | "editor" | "viewer";type User = {id: number;name: string;role: UserRole;};const alice: User = {id: 1,name: "Alice",role: "admin",};console.log(alice);
This User
type says: a user must have a role and that role must be one of the specific values we allow. This prevents bugs like accidentally assigning "Admin"
or "superuser"
—they’re not in the set, and TypeScript won’t let ...