Skip to content

Type Aliases

Type aliases let you create custom types for better readability and reusability. They're a way to give meaningful names to complex types and make your code more self-documenting.

Basic Type Aliases

You can create aliases for simple types:

ts
type NumberArray = number[];
type StringArray = string[];

// Usage:
let scores: NumberArray = [85, 92, 78, 96];
let weights: NumberArray = [175, 105, 210];

let names: StringArray = ["Alice", "Bob", "Charlie"];
let colours: StringArray = ["blue", "red", "green", "purple", "orange"];

👉 The convention is to use CamelCase (starting with a capital letter) for all type aliases (e.g., NumberArray, not number_array).

Function Type Aliases

Type aliases are especially useful for function types:

ts
type SimpleCallback = (data: string) => void;
type MathOperation = (a: number, b: number) => number;

// Usage:
const logMessage: SimpleCallback = (message) => console.log(message);

const add: MathOperation = (a, b) => a + b;

Practical Example: Callback Function

This example demonstrates how type aliases can simplify complex function signatures. By creating a Callback type, the function parameter becomes much clearer and easier to understand:

ts
type Callback = (data: string) => void;

function doSomething(callback: Callback) {
  callback("Hello");
}

doSomething((data) => {
  console.log(data); // Output: Hello
});

Object Type Aliases

Create aliases for object shapes:

ts
type Point = { x: number; y: number };
type Shape = { colour: string };
type User = { 
  name: string; 
  age: number; 
  email: string; 
};

// Usage:
let position: Point = { x: 10, y: 20 };
let circle: Shape = { colour: "red" };
let person: User = { name: "Alice", age: 30, email: "alice@example.com" };

Practical Example: Point Distance Calculation

This example shows how type aliases make function signatures more readable and self-documenting. Instead of writing the object shape inline, we define a Point type that clearly represents a 2D coordinate:

ts
type Point = { x: number; y: number };

function distance(p1: Point, p2: Point): number {
  return Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2);
}

const a: Point = { x: 0, y: 0 };
const b: Point = { x: 3, y: 4 };

let d = distance(a, b);
console.log(d); // Output: 5

// You can also pass objects directly that match the Point structure:
d = distance({ x: 0, y: 0 }, { x: 3, y: 4 });
console.log(d); // Output: 5