TypeScript ยท Chapter 15 of 44

TypeScript Type Aliases

A type alias lets you give a name to any type, making complex types reusable and your code more readable. You create one with the `type` keyword followed by a name and an equals sign.

Type aliases can represent primitives, unions, tuples, or object shapes, and once defined, the alias name can be used anywhere that type is needed instead of repeating the full type definition.

Syntax
type ID = string | number;
type User = { name: string; age: number };

Creating a type alias

Writing `type ID = string | number;` creates a reusable name for that union. You can then use `ID` as a type anywhere in your code instead of repeating the union.

Object type aliases

Type aliases are frequently used for object shapes, such as `type User = { name: string; age: number };`, which documents exactly what properties a User object should have.

Example 1 (typescript)
type ID = string | number;

function printId(id: ID) {
  console.log(`ID: ${id}`);
}
printId(42);
Output
ID: 42

ID is a reusable alias for the union type string | number.

Example 2 (typescript)
type User = { name: string; age: number };

const u: User = { name: "Kim", age: 28 };
console.log(`${u.name} is ${u.age}`);
Output
Kim is 28

The User type alias documents the exact shape an object must have.

Key points

  • Type aliases are created with the `type` keyword.
  • They can name unions, tuples, primitives, or object shapes.
  • Aliases make complex types reusable and easier to read.
  • Once defined, an alias can be used anywhere a type is expected.
๐Ÿ’ก Note: Type aliases and interfaces overlap a lot for object shapes; the next lesson compares the two.

๐Ÿ“ Quick Quiz

1. Which keyword creates a type alias?

2. What can a type alias represent?

3. Why use type aliases?