← Back to TypeScript Course | Chapter 5: Type Aliases and Union Types | Lesson 1 of 9

Type Aliases

A type alias lets you create a reusable name for a TypeScript type. Type aliases make complex types easier to read, reuse, and maintain throughout your program.

Creating a Type Alias

The type keyword, followed by a name and an equals sign, defines a type alias, such as type ID = string | number. The alias can then be used anywhere you would normally write out the original type, keeping repeated or complex types readable and consistent.

Example: Creating a Type Alias

typescript
type ID = string | number;
let userId: ID = 42;
userId = "abc";
console.log(userId);

Object Type Aliases

A type alias can describe the structure of an object, functioning much like an interface for this purpose. This is useful whenever multiple variables or functions across a codebase need to work with objects sharing the exact same set of properties.

Example: Object Type Aliases

typescript
type User = {
  name: string;
  age: number;
};
const user: User = { name: "Tia", age: 29 };
console.log(user);

Type Aliases for Functions

A type alias can describe a function's full signature, capturing both its parameter types and its return type in one reusable name. This makes function types easy to pass around, store in variables, and keep function declarations that use them much easier to read.

Example: Type Aliases for Functions

typescript
type MathOp = (a: number, b: number) => number;
const add: MathOp = (a, b) => a + b;
console.log(add(2, 3));

Combining Type Aliases

Type aliases can be combined with other types, most commonly through unions or intersections, to build more expressive structures out of smaller, reusable pieces. This encourages building larger types compositionally instead of writing one giant inline type.

Example: Combining Type Aliases

typescript
type Timestamped = { createdAt: string };
type Named = { name: string };
type Record = Timestamped & Named;
const record: Record = { createdAt: "2024", name: "Log" };
console.log(record);

Reusable Domain Types

Type aliases are especially valuable for naming core domain concepts in an application, such as User, Product, Order, or a specific configuration shape. Reusing a single named alias everywhere those concepts appear keeps related code consistent and easy to update in one place.

Example: Reusable Domain Types

typescript
type Product = {
  id: number;
  name: string;
  price: number;
};
function printProduct(p: Product) {
  console.log(`${p.name}: $${p.price}`);
}
printProduct({ id: 1, name: "Pen", price: 2 });
🔒

Chapter Quiz — Complete all 9 topics to unlock

0/9 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.