0
0
Typescriptprogramming~5 mins

Interface vs type alias decision in Typescript

Choose your learning style9 modes available
Introduction

Interfaces and type aliases both describe shapes of data in TypeScript. Choosing between them helps keep your code clear and easy to work with.

When you want to describe the shape of an object that might be extended later.
When you need to create a union or intersection of types.
When you want to define a simple alias for a type like a string or number.
When you want to use declaration merging to add properties later.
When you want to describe complex types like tuples or mapped types.
Syntax
Typescript
interface InterfaceName {
  propertyName: type;
}

type TypeAliasName = typeExpression;

Interfaces describe object shapes and can be extended or merged.

Type aliases can name any type, including primitives, unions, and tuples.

Examples
This interface describes an object with a name and age.
Typescript
interface Person {
  name: string;
  age: number;
}
This type alias defines ID as either a string or a number.
Typescript
type ID = string | number;
Interfaces can extend other interfaces to add more properties.
Typescript
interface Animal {
  species: string;
}

interface Dog extends Animal {
  breed: string;
}
This type alias defines a tuple for coordinates with two numbers.
Typescript
type Coordinates = [number, number];
Sample Program

This program shows how to create an interface and a type alias with the same shape, then use them to type objects.

Typescript
interface User {
  id: number;
  name: string;
}

type UserAlias = {
  id: number;
  name: string;
};

const user1: User = { id: 1, name: "Alice" };
const user2: UserAlias = { id: 2, name: "Bob" };

console.log(user1);
console.log(user2);
OutputSuccess
Important Notes

Interfaces support declaration merging, so you can add properties later by declaring the same interface again.

Type aliases cannot be reopened once declared.

Use interfaces for objects you expect to extend or implement in classes.

Summary

Interfaces are best for describing object shapes and can be extended or merged.

Type aliases can name any type, including unions and tuples, but cannot be merged.

Choose based on whether you need extension, merging, or complex type expressions.