On this page

TypeScript Interfaces: Complete Guide

Updated on August 3, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Interfaces are one of the most important tools in TypeScript. They allow you to define the shape that an object must have — what properties it contains, what types those properties have, and what methods it implements. Think of an interface as a contract: if an object satisfies the contract, TypeScript will allow you to use it wherever that interface is expected.


What Is an Interface?​

In TypeScript, an interface is a way to describe the shape of an object. It specifies what properties and methods an object must have, without providing any implementation. You can think of it as a blueprint or a contract that objects must follow.

The core purpose of an interface is to enforce consistency. When you define an interface, you are telling TypeScript: “Any object that claims to be of this type must have at least these properties, with these types.” TypeScript then checks that objects you pass around actually meet these requirements.

A Simple Example​

Imagine you have a function that prints a label. Without TypeScript, you might write something like this in plain JavaScript:


function printLabel(labeledObj) {

  console.log(labeledObj.label);

}



let myObj = { size: 10, label: "Size 10 Object" };

printLabel(myObj);

This works, but there is no guarantee that labeledObj actually has a label property. If someone calls printLabel with an object that doesn't have a label, the code will fail at runtime.

With TypeScript, you can use an interface to describe the required shape:


interface LabeledValue {

  label: string;

}



function printLabel(labeledObj: LabeledValue) {

  console.log(labeledObj.label);

}



let myObj = { size: 10, label: "Size 10 Object" };

printLabel(myObj); // ✅ Works — myObj has a 'label' property

The LabeledValue interface states that any object of this type must have a label property of type string. The printLabel function now requires its argument to satisfy this interface.

Notice that myObj has an extra size property. TypeScript only checks that the required properties are present and match the required types. Extra properties are allowed, as long as they don't violate the contract.

Interface Syntax​

The syntax for defining an interface is straightforward:


interface InterfaceName {

  propertyName: propertyType;

  anotherProperty: anotherType;

}

You use the interface keyword, followed by the name of the interface (by convention, written in PascalCase), and then a set of property definitions inside curly braces.

Here is a more complete example:


interface Person {

  firstName: string;

  lastName: string;

  age: number;

}



function greet(person: Person): string {

  return `Hello, ${person.firstName} ${person.lastName}!`;

}



const user = { firstName: "Alice", lastName: "Smith", age: 30 };

console.log(greet(user)); // Output: Hello, Alice Smith!

The Person interface defines three required properties: firstName (string), lastName (string), and age (number). Any object passed to greet must have all three.


Optional Properties​

Not all properties of an interface need to be required. Sometimes, an object may have a property only under certain conditions. TypeScript allows you to mark properties as optional using a question mark (?).


interface SquareConfig {

  color?: string;

  width?: number;

}



function createSquare(config: SquareConfig): { color: string; area: number } {

  let newSquare = { color: "white", area: 100 };

  if (config.color) {

    newSquare.color = config.color;

  }

  if (config.width) {

    newSquare.area = config.width * config.width;

  }

  return newSquare;

}



let mySquare = createSquare({ color: "black" });

// mySquare is { color: "black", area: 100 }

In this example, both color and width are optional. You can call createSquare with only color, only width, both, or neither. The function checks for the existence of each property before using it.

The advantage of optional properties is that they allow you to describe flexible objects while still preventing the use of properties that are not part of the interface. If you mistype a property name, TypeScript will catch the error:


let mySquare = createSquare({ clor: "black" });

// Error: Property 'clor' does not exist on type 'SquareConfig'. Did you mean 'color'?

This early error detection saves you from bugs that would otherwise only appear at runtime.


Readonly Properties​

Some properties should be set only once, when an object is first created, and never changed afterward. TypeScript provides the readonly modifier for this purpose:


interface Point {

  readonly x: number;

  readonly y: number;

}



let p: Point = { x: 10, y: 20 };

p.x = 30; // ❌ Error: Cannot assign to 'x' because it is a read-only property

Once you assign a value to a readonly property, you cannot change it. This is useful for defining constants or values that should remain immutable throughout the lifetime of an object.

TypeScript also provides a utility type Readonly<T> that makes all properties of a type read-only. This is covered in more advanced lessons.


Function Types with Interfaces​

Interfaces can also describe function types. This is useful when you want to define the shape of a function — what parameters it takes and what it returns:


interface SearchFunction {

  (source: string, subString: string): boolean;

}



let mySearch: SearchFunction = function (

  source: string,

  subString: string,

): boolean {

  let result = source.search(subString);

  return result > -1;

};



console.log(mySearch("Hello world", "world")); // true

console.log(mySearch("Hello world", "goodbye")); // false

The SearchFunction interface describes a function that takes two string parameters and returns a boolean. The variable mySearch is then assigned a function that matches this signature.

Notice that the parameter names in the function do not need to match the names in the interface — only the types matter. TypeScript checks that the function is compatible with the interface.


Indexable Types​

Sometimes you need to describe types that can be indexed into, like arrays or objects with dynamic property names. Interfaces can describe indexable types using an index signature:


interface StringArray {

  [index: number]: string;

}



let myArray: StringArray = ["Alice", "Bob", "Charlie"];

let firstItem: string = myArray[0]; // "Alice"

The [index: number]: string syntax means that when you index into the object with a number, you get back a string. This is how arrays work in TypeScript.

You can also use string index signatures for objects with dynamic keys:


interface Dictionary {

  [key: string]: number;

}



let scores: Dictionary = {

  Alice: 95,

  Bob: 87,

  Charlie: 92,

};



let aliceScore: number = scores["Alice"]; // 95

This interface says that any property name (string) maps to a number value.

When you have both string and number index signatures, the number index's return type must be a subtype of the string index's return type. This is because JavaScript converts number keys to strings when indexing.


Extending Interfaces​

One of the most powerful features of interfaces is that they can extend other interfaces. This allows you to build new interfaces that inherit all the properties of an existing interface, and then add more.

Basic Extension​


interface Person {

  name: string;

  age: number;

}



interface Employee extends Person {

  employeeId: string;

  department: string;

}



const worker: Employee = {

  name: "Alice",

  age: 30,

  employeeId: "EMP001",

  department: "Engineering",

};

The Employee interface extends Person, so it automatically includes name and age, plus its own employeeId and department. This is a clean way to reuse and build upon existing type definitions.

Multiple Inheritance​

Interfaces can extend multiple interfaces at once:


interface Timestamped {

  createdAt: Date;

  updatedAt: Date;

}



interface Identified {

  id: string;

}



interface User extends Timestamped, Identified {

  name: string;

  email: string;

}



const user: User = {

  id: "1",

  name: "Alice",

  email: "[email protected]",

  createdAt: new Date(),

  updatedAt: new Date(),

};

This is extremely useful for modeling:

When you extend multiple interfaces, if they have conflicting property types, TypeScript will raise an error.

Extending Type Aliases​

Interfaces can even extend type aliases — as long as the alias resolves to an object type:


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



interface Point extends Coordinates {

  label: string;

}



const p: Point = { x: 10, y: 20, label: "Origin" };

This flexibility makes interfaces a great choice for building layered, evolving models.


Declaration Merging​

One of the most unique features of interfaces is declaration merging. If you declare the same interface multiple times, TypeScript automatically merges them into a single definition. This is something type aliases cannot do.

How Merging Works​


interface Settings {

  theme: string;

}



interface Settings {

  language: string;

}



// The resulting interface is:

// interface Settings {

//     theme: string;

//     language: string;

// }

The merge mechanically joins the members of both declarations into a single interface with the same name.


interface Box {

  height: number;

  width: number;

}



interface Box {

  scale: number;

}



let box: Box = { height: 5, width: 6, scale: 10 }; // âś… Valid

Rules for Merging​

Why Merging Matters​

Declaration merging enables several powerful patterns:

1. Augmenting third‑party types

You can extend existing library types without modifying the original source code:


declare module "express-serve-static-core" {

  interface Request {

    userId?: string;

  }

}

This adds userId to Express's Request type — without modifying the library.

2. Splitting large interfaces across files

In large codebases, you can define parts of an interface in different files, and TypeScript merges them automatically.

3. Extending interfaces in a modular way

Declaration merging allows library authors to provide extension points that users can leverage.

Important Note​

Type aliases cannot merge. If you try to declare the same type alias twice, TypeScript raises an error:


type Puppy = { color: string };

type Puppy = { toys: number }; // ❌ Duplicate identifier 'Puppy'

If you need merging or augmentation, use an interface.


Interfaces vs Type Aliases​

TypeScript provides two main tools for declaring the shape of an object: interface and type aliases. They are very similar, and for most common cases, they act the same.

Key Differences​

FeatureInterfaceType AliasDeclaration merging✅ Yes — can be declared multiple times❌ No — cannot be reopenedExtends keyword✅ Yes — extends❌ No — uses intersections (&)Can represent primitives, unions, tuples❌ No — object shapes only✅ Yes — any typeError messagesOften more readableCan be more verbosePerformanceGenerally faster for the compilerCan be slower for complex types

The "Open" vs "Closed" Distinction​

Interfaces are open — you can extend them by declaring them again. Type aliases are closed — once defined, they cannot be changed.

For publicly exposed types in libraries or large codebases, interfaces are generally the better choice because they can be extended by consumers without breaking changes.

When to Use Interfaces​

The TypeScript team recommends using interfaces by default because they provide:

When to Use Type Aliases​

Use type aliases when you need:


Structural Typing​

This is one of the most important conceptual differences between TypeScript and languages like Java, C#, or Rust.

What Is Structural Typing?​

TypeScript uses structural typing — a type is compatible with another type if it has the same shape (members), regardless of its name. This is in contrast to nominal typing, where types are compatible only if they have the same declared identity.

In TypeScript, if a type is "shaped like a duck, it's a duck" — a concept sometimes called "duck typing" or "structural subtyping".

Structural Typing in Action​

Example: Two types with the same shape


interface Point {

  x: number;

  y: number;

}



interface Vector {

  x: number;

  y: number;

}



const p: Point = { x: 1, y: 2 };

const v: Vector = p; // ✅ Allowed — same shape

Even though Point and Vector are different names, they are structurally identical.

Example: Classes and interfaces


interface Pet {

  name: string;

}



class Dog {

  name: string;

  constructor(name: string) {

    this.name = name;

  }

}



let pet: Pet = new Dog("Lassie"); // âś… Allowed

In a nominally‑typed language like Java or C#, this would be an error because Dog does not explicitly declare that it implements Pet. TypeScript's structural typing allows this because Dog has the required name property.

Why Structural Typing Matters​

1. It makes TypeScript feel natural for JavaScript developers

JavaScript is dynamic and shape‑based; TypeScript embraces that.

2. It enables flexible, composable APIs

You don't need rigid class hierarchies or explicit implements declarations.

3. It reduces boilerplate

You don't need to explicitly declare that a type implements an interface — the shape alone is sufficient.

4. It makes testing easier

Mocks and stubs only need the required properties — not the exact type name.

When Structural Typing Can Surprise You​

Because TypeScript checks shape, not name, two unrelated types can be accidentally compatible:


interface Credentials {

  username: string;

  password: string;

}



interface ApiKey {

  username: string;

  key: string;

}



const key: ApiKey = { username: "a", key: "123" };

const creds: Credentials = key; // ⚠️ Allowed (surprisingly!)

This is allowed because both types have a username: string property. If you need stricter checks, you can:

Extra Properties Are Allowed When Assigning to a Wider Type​


interface Person {

  name: string;

}



const obj = { name: "Alice", age: 30 };

const p: Person = obj; // ✅ Allowed — extra properties are ignored

The compiler only checks that the required properties are present and match the required types.


Putting It All Together​

Here's a realistic example combining interface extension, merging, and structural typing:


// Base interfaces

interface Entity {

  id: string;

}



interface Timestamped {

  createdAt: Date;

  updatedAt: Date;

}



// Extend multiple interfaces

interface User extends Entity, Timestamped {

  name: string;

  email: string;

}



// Declaration merging — add an optional field

interface User {

  isAdmin?: boolean;

}



// Structural typing in action

function printUser(u: User) {

  console.log(u.id, u.name, u.createdAt);

}



// This object satisfies the User shape, even without explicit 'implements'

const obj = {

  id: "1",

  name: "Alice",

  email: "[email protected]",

  createdAt: new Date(),

  updatedAt: new Date(),

  isAdmin: true,

};



printUser(obj); // âś… Works due to structural typing

This example demonstrates:


Summary​

Interfaces are one of the most powerful modeling tools in TypeScript. Mastering them unlocks cleaner, safer, and more expressive code.

In this lesson, you learned:

1. What Interfaces Are and How to Use Them​

2. Advanced Interface Features​

3. Structural Typing​

4. Interfaces vs Type Aliases​

Frequently Asked Questions on TypeScript Interfaces​

What is an interface in TypeScript?

An interface in TypeScript is a way to describe the shape of an object. It defines what properties and methods an object must have, without providing any implementation. It acts as a contract that objects must follow, and TypeScript checks that objects passed around actually meet these requirements.

How do I define an interface in TypeScript?

Use the `interface` keyword followed by the interface name (PascalCase by convention) and a set of property definitions inside curly braces. For example: `interface Person { name: string; age: number; }`. This defines an interface that requires any object of this type to have a `name` property of type `string` and an `age` property of type `number`.

What are optional properties in TypeScript interfaces?

Optional properties are marked with a question mark (`?`) after the property name. They allow an object to have a property only under certain conditions. For example, `interface Config { color?: string; width?: number; }` means both `color` and `width` are optional. If you mistype a property name, TypeScript will catch the error.

What is the purpose of `readonly` properties in TypeScript interfaces?

The `readonly` modifier prevents a property from being changed after its initial assignment. It is useful for defining constants or values that should remain immutable. For example, `interface Point { readonly x: number; readonly y: number; }` means `x` and `y` cannot be reassigned once set.

Can TypeScript interfaces describe function types?

Yes. Interfaces can describe function types by specifying the parameter types and return type. For example, `interface SearchFunction { (source: string, subString: string): boolean; }` describes a function that takes two string parameters and returns a boolean.

What are indexable types in TypeScript interfaces?

Indexable types use an index signature to describe types that can be indexed into, like arrays or objects with dynamic property names. For example, `interface StringArray { [index: number]: string; }` means when you index with a number, you get a string. You can also use string index signatures for objects with dynamic keys.

How do I extend an interface in TypeScript?

Use the `extends` keyword. For example, `interface Employee extends Person { employeeId: string; }` creates a new interface that includes all properties from `Person` plus `employeeId`. Interfaces can extend multiple interfaces at once, which is useful for modeling database entities, domain models, and API response shapes.

What is declaration merging in TypeScript interfaces?

Declaration merging is a unique feature of interfaces where if you declare the same interface multiple times, TypeScript automatically merges them into a single definition. This allows you to augment third‑party types, split large interfaces across files, and provide extension points for library consumers. Type aliases cannot merge.

What is the difference between an interface and a type alias?

Interfaces support declaration merging and use the `extends` keyword, while type aliases do not support merging and use intersections (`&`). Interfaces can only represent object shapes, while type aliases can represent primitives, unions, tuples, and more complex types. Interfaces generally provide better error messages and faster compiler performance.

When should I use an interface versus a type alias?

Use interfaces by default for object shapes because they provide better error messages, faster compiler performance, declaration merging, and natural interoperability with classes. Use type aliases for union types, tuple types, primitive types, mapped or conditional types, and complex type compositions that go beyond what interfaces can express.

What is structural typing in TypeScript?

Structural typing means a type is compatible with another type if it has the same shape (members), regardless of its name. For example, two interfaces with the same properties are interchangeable even if they have different names. This makes TypeScript flexible and JavaScript‑friendly, reduces boilerplate, and makes testing easier.

Why can my code sometimes use an object that doesn't explicitly implement an interface?

Because TypeScript uses structural typing. If an object has the required properties with the correct types, it is automatically compatible with the interface even without an explicit `implements` declaration. Extra properties are allowed as long as required ones are present.

What are branded types and why would I use them?

Branded types are a way to create stricter type checking when structural typing might allow accidental compatibility. They add a unique property or 'brand' to differentiate otherwise identical types. For example, you can add a `_brand` property to distinguish a `UserId` from a `CustomerId`, even though both are strings.

Can I use interfaces with classes in TypeScript?

Yes. Classes can implement interfaces using the `implements` keyword to ensure they provide all required members. This is useful for enforcing contracts between components. Classes can also implement multiple interfaces.

What is the difference between `extends` and `implements` in TypeScript?

`extends` is used for class inheritance (subclassing) — a class inherits from another class and gets its implementation. `implements` is used for class-interface relationships — a class must provide its own implementation of the interface's members. A class can extend one class and implement multiple interfaces.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Interfaces, Classes & OOP in TypeScript

Next

Classes