Lesson 5 of 15

Type Aliases

Type Aliases

The type keyword creates an alias for any type — primitives, unions, objects, functions:

type Name = string;
type Age = number;
type ID = string | number;   // union type

Object Type Aliases

type can define object shapes just like interface:

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

When to Use type vs interface

Both type and interface can define object shapes. The key difference:

  • interface can be extended with extends and merged via declaration merging
  • type can represent unions, intersections, and primitives that interface cannot

In practice: use interface for object shapes, type for everything else.

Union Types

A union type accepts multiple possible types:

type StringOrNumber = string | number;

function format(val: StringOrNumber): string {
    return "Value: " + val;
}

console.log(format("hello"));  // Value: hello
console.log(format(42));       // Value: 42

Your Task

Define type ID = string | number. Write function formatID(id: ID): string that returns "ID:" + id.

TypeScript loading...
Loading...
Click "Run" to execute your code.