Type Aliases and Index Signatures
Explore how TypeScript's type aliases improve code clarity by naming reusable object shapes, union types, and function signatures. Understand how index signatures handle objects with unknown keys while ensuring consistent value types. This lesson guides you through modeling flexible data structures and defining robust types that help prevent bugs and support scalable applications.
We'll cover the following...
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:
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 ...