Sitemap

TS type vs. interface

2 min readDec 11, 2023

--

In TypeScript, both `type` and `interface` are used to define the shape of an object or function. They are quite similar but have some differences that make them suitable for different scenarios.

Press enter or click to view image in full size

Interface

An `interface` in TypeScript is used to define the shape of an object. It can include properties and method signatures. Interfaces are often used to define contracts within your code as well as contracts with code outside of your project.

Extending: Interfaces can extend one or more other interfaces. This makes them ideal for defining reusable abstractions.

Merging: TypeScript supports declaration merging for interfaces. If you declare an interface with the same name more than once, TypeScript will treat it as a single interface.

interface User {
name: string;
}
interface User {
age: number;
}
// User is treated as: { name: string; age: number; }

Implementation: Classes can implement interfaces. This is a way to enforce certain structures on classes.

interface User {
name: string;
}

class Employee implements User {
name: string;
// …
}

Type

A `type` declaration is a more general construct in TypeScript. It can represent not only the shape of an object but also a union, intersection, primitive, or any other type you can think of.

Get Itay Gold’s stories in your inbox

Join Medium for free to get updates from this writer.

Unions and Intersections: Types are more versatile when it comes to combining existing types.

type Action = 'create' | 'update';
type Result = { success: boolean } | { error: string };

Cannot be redeclared: Unlike interfaces, type aliases cannot be reopened to add new properties.

Non-object types: Types can define things other than object shapes, such as union and intersection types, tuple types, and more.

type ID = string | number; 
type Point = [number, number];

Choosing Between `type` and `interface`

Use `interface`:
— You need to define a contract for an object or a class (e.g., for dependency injection).
— You want to take advantage of declaration merging.

Use `type`:
— You need to use a union or intersection type.
— You want to define tuple types, or other specific use cases that aren’t just about the shape of an object.

Interchangeability: In many cases, `type` and `interface` can be used interchangeably. Preference for one over the other can often come down to style, specific requirements, or the need for specific features (like unions or declaration merging).

In practice, many TypeScript projects use a mix of both `interfaces` and `types` depending on the specific needs of the code being written. The choice often comes down to the specific features you need and the coding style preferences of your team.

--

--

Itay Gold
Itay Gold

Written by Itay Gold

I'm entrepreneurial-spirited, a pioneering technologist with 10+ years of experience in Full Stack Software Development.