Skip to content

Objects, Interfaces, and Type Aliases

In TypeScript, you can describe what an object looks like and how your data is built. You do this using interfaces and type aliases. These help you set clear rules for your code, so it is easier to read and fix later. In this section, we will learn how to write object types, use interfaces to describe the shape of objects, make type aliases for more complex types, and understand the difference between interfaces and type aliases. By the end of this section, you will understand how to work with objects, interfaces, and type aliases in TypeScript.

let user: { name: string; age: number } = {
name: "Sahil",
age: 22,
};

This works fine, but it is hard to reuse this same type again somewhere else in your code.

interface User {
name: string;
age: number;
}

Use an interface when you want to clearly describe the shape of an object.

type User = {
name: string;
age: number;
};

A type alias can also be used for unions, tuples, and other complex type combinations, not just plain objects.

  • Good for object-oriented style design
  • Supports declaration merging (you can reopen it later and add more to it)
  • Commonly used for class contracts
interface User {
name: string;
}
interface User {
age: number;
}

Now User has both name and age properties. This is called declaration merging - TypeScript automatically joins both interface blocks into one.

type A = { name: string };
type B = { age: number };
type Person = A & B;

Person must have all the properties from both A and B. The & symbol joins the two types together into one bigger type.

graph LR A[Type A] --> C[Intersection Type] B[Type B] --> C C --> D[Combined Requirements]
interface Calculator {
add(a: number, b: number): number;
}

Method signatures (the function rules written inside an interface) make it clear what a piece of code should do, without writing the actual logic.