TypeScript Type Aliases

A type alias creates a custom name for any type — simple, complex, union, intersection, or function. Once defined, the alias can be used wherever that type is needed. Type aliases reduce repetition, improve readability, and make complex type definitions reusable across the entire codebase.

What Is a Type Alias?

  Without alias — repeated everywhere:
  let userId: number | string;
  let productId: number | string;
  let orderId: number | string;

  With alias — defined once, used everywhere:
  type ID = number | string;

  let userId: ID;
  let productId: ID;
  let orderId: ID;

Creating a Type Alias

// Alias for a primitive type
type Username = string;
type Score = number;
type IsActive = boolean;

let user: Username = "Saranya";
let examScore: Score = 88;
let active: IsActive = true;

Type Alias for Objects

// Define the shape once
type Address = {
    street: string;
    city: string;
    state: string;
    pincode: number;
};

// Use it wherever needed
let homeAddress: Address = {
    street: "12 MG Road",
    city: "Bengaluru",
    state: "Karnataka",
    pincode: 560001
};

let officeAddress: Address = {
    street: "45 Sector 18",
    city: "Noida",
    state: "Uttar Pradesh",
    pincode: 201301
};

console.log(homeAddress.city);   // Bengaluru
console.log(officeAddress.city); // Noida

Type Alias for Union Types

// An ID can be a number or a string
type ID = number | string;

// A response status can be one of several strings
type ResponseStatus = "success" | "error" | "loading" | "idle";

let customerId: ID = 1001;
customerId = "CUST-1001";  // Also valid

let apiStatus: ResponseStatus = "loading";
apiStatus = "success";
apiStatus = "failed"; // Error: Type '"failed"' is not assignable to type 'ResponseStatus'

Type Alias for Function Types

// Define a function signature type
type MathFunc = (a: number, b: number) => number;
type Formatter = (value: string) => string;

let add: MathFunc = (a, b) => a + b;
let subtract: MathFunc = (a, b) => a - b;

let toUpper: Formatter = (s) => s.toUpperCase();
let trim: Formatter = (s) => s.trim();

console.log(add(10, 5));         // 15
console.log(toUpper("hello"));   // HELLO

Type Alias for Arrays and Tuples

// Array alias
type Marks = number[];
type Names = string[];

let subjectMarks: Marks = [85, 90, 78];
let classNames: Names = ["Alpha", "Beta", "Gamma"];

// Tuple alias
type Coordinate = [number, number];
type EmployeeRecord = [string, number, string]; // [name, id, department]

let point: Coordinate = [25.5, 80.3];
let emp: EmployeeRecord = ["Rajan", 3001, "Marketing"];

Intersecting Type Aliases

Two type aliases combine into one using the & operator. The resulting type requires properties from all combined types.

type HasName = {
    name: string;
};

type HasAge = {
    age: number;
};

type HasEmail = {
    email: string;
};

// Combine all three
type ContactPerson = HasName & HasAge & HasEmail;

let contact: ContactPerson = {
    name: "Usha Mehta",
    age: 35,
    email: "usha@example.com"
};

console.log(contact.name + " | " + contact.email);
// Output: Usha Mehta | usha@example.com

Extending Type Aliases

Type aliases extend other type aliases using intersection (&), creating a composed type without modifying the original.

type BasicUser = {
    userId: number;
    username: string;
};

type AdminUser = BasicUser & {
    adminLevel: number;
    permissions: string[];
};

let admin: AdminUser = {
    userId: 1,
    username: "superadmin",
    adminLevel: 3,
    permissions: ["read", "write", "delete"]
};

console.log(admin.username);     // superadmin
console.log(admin.permissions);  // ["read", "write", "delete"]

Recursive Type Aliases

A type alias can refer to itself, creating a recursive type. This is useful for tree structures and nested menus.

type MenuItem = {
    label: string;
    link: string;
    children?: MenuItem[];  // Recursive — a menu can have sub-menus
};

let navigation: MenuItem[] = [
    {
        label: "Courses",
        link: "/courses",
        children: [
            { label: "TypeScript", link: "/courses/typescript" },
            { label: "JavaScript", link: "/courses/javascript" }
        ]
    },
    {
        label: "About",
        link: "/about"
    }
];

console.log(navigation[0].children?.[0].label); // TypeScript

Type Alias vs Interface

FeatureType AliasInterface
Object typesYesYes
Union typesYes (type A = B | C)No
PrimitivesYes (type Name = string)No
TuplesYesPossible but uncommon
Declaration mergingNoYes
Extension syntax& intersectionextends keyword

Practical Example

// Course platform — reusable type aliases
type CourseLevel = "Beginner" | "Intermediate" | "Advanced";
type CourseStatus = "Draft" | "Published" | "Archived";
type Duration = { hours: number; minutes: number };

type Course = {
    readonly courseId: number;
    title: string;
    instructor: string;
    level: CourseLevel;
    status: CourseStatus;
    duration: Duration;
    price: number;
    isFree: boolean;
};

let course: Course = {
    courseId: 1001,
    title: "TypeScript from Zero to Hero",
    instructor: "Deepa Nair",
    level: "Beginner",
    status: "Published",
    duration: { hours: 12, minutes: 30 },
    price: 999,
    isFree: false
};

console.log(course.title + " | Level: " + course.level);
// Output: TypeScript from Zero to Hero | Level: Beginner

console.log("Duration: " + course.duration.hours + "h " + course.duration.minutes + "m");
// Output: Duration: 12h 30m

Leave a Comment