Lesson 9 of 20

Type Aliases

Creating Type Aliases

Type aliases let you create custom names for any type. They work similarly to interfaces but can represent more than just object shapes.

Example
// Simple type alias
type ID = string | number;
type Username = string;

let userId: ID = 123;
let userName: Username = "alice";

// Object type alias
type Point = {
  x: number;
  y: number;
};

const origin: Point = { x: 0, y: 0 };

// Function type alias
type Formatter = (input: string) => string;
const toUpper: Formatter = (s) => s.toUpperCase();

Interfaces vs Type Aliases

Both can describe object shapes, but they have differences. Interfaces can be extended and merged; type aliases can represent unions, tuples, and primitives.

Example
// Interface — can be extended and merged
interface Animal {
  name: string;
}
interface Animal {
  sound: string; // declaration merging — both properties required
}

// Type alias — can represent unions and intersections
type Shape = Circle | Rectangle;
type Circle = { kind: "circle"; radius: number };
type Rectangle = { kind: "rect"; width: number; height: number };

// Intersection type (combine types)
type Employee = User & { department: string };

Template Literal Types

TypeScript supports template literal types for creating string patterns at the type level.

Example
// Template literal types
type Color = "red" | "green" | "blue";
type Shade = "light" | "dark";

type ColorVariant = `${Shade}-${Color}`;
// "light-red" | "light-green" | "light-blue" | "dark-red" | ...

let c: ColorVariant = "light-red"; // OK
let d: ColorVariant = "bright-red"; // Error

// Event handler pattern
type EventName = `on${Capitalize<string>}`;
let handler: EventName = "onClick"; // OK