Muhammad Fari Madyan
Hire me
Node.js & TS · part 11 of 13

Node.js & TypeScript Backend Part 11: type vs interface — Declaration Merging, extends vs & and Consistency

Part eleven of a Node.js & TypeScript series that opens with a quiz: where type and interface are the same, unions and tuples that need type, declaration merging to augment Express.Request, an extends conflict that is rejected vs an intersection that quietly becomes never, and the consistent-type-definitions rule.

Muhammad Fari Madyan

· 7 min read

Baca dalam Bahasa Indonesia →

Opening: 30 Comments and One never

A small pull request gets 30 comments. Nearly all of them are about one thing: "Why type? We use interface here." Then the reply: "But type is more flexible." Two days go by.

The irony is that the same pull request let a bug through:

TS
type DasarT = { id: string };
type TurunanT = DasarT & { id: number };

Nobody objected to that line. id on TurunanT quietly became never, and nobody found out until someone tried to create one.

Had the code used interface ... extends, TypeScript would have rejected it on the declaration line. So there is a real difference, just not where the argument was. This part sorts out when type and interface truly differ, and when it is only a matter of taste.


Warm-Up Quiz: Do You Still Remember?

Answer first. All correct? Jump to the Summary. Missed one? Let's refresh the material.

Question 1. What happens?

TS
interface Pengguna { id: string }
interface Pengguna { nama: string }
const u: Pengguna = { id: 'u1', nama: 'Fari' };
  • A. A compile error: duplicate name
  • B. The two declarations merge, so Pengguna has id and nama
Show the answer to question 1

B. This is declaration merging: interfaces with the same name in the same scope are merged into one.

Question 2. What if both are type?

TS
type Event = { id: string };
type Event = { nama: string };
  • A. They merge too
  • B. A compile error
Show the answer to question 2

B. error TS2300: Duplicate identifier 'Event'. A type is an alias. One name, one definition.

Question 3. When does TypeScript complain about this code?

TS
type DasarT = { id: string };
type TurunanT = DasarT & { id: number };
const x: TurunanT = { id: 1 };
  • A. On the type TurunanT line
  • B. Only on the const x line
Show the answer to question 3

B. An intersection & does not reject conflicts. id becomes string & number, which is never. The error only appears when it is used: Type 'number' is not assignable to type 'never'. With interface Turunan extends Dasar { id: number }, the error appears at the declaration.

Question 4. Which can only be written with type?

  • A. { id: string; nama: string }
  • B. 'pending' | 'paid' | 'failed'
Show the answer to question 4

B. Unions need type. So do tuples, mapped types, conditional types and aliases for primitives. An interface only describes object shapes.

Question 5. You want to add a pengguna (user) field to Express's Request, so req.pengguna is recognised in every handler. Which do you use?

  • A. type
  • B. interface
Show the answer to question 5

B. Adding a field to another library's type needs declaration merging, and only interface can do that.

What did you score? Let's take them apart.


1. Mostly, They Are the Same

Three areas: only type (unions, tuples, mapped types, conditional types, primitive aliases), both (object shapes, optional, readonly, generics, implements), and only interface (declaration merging, library augmentation). A conflict when extending: interface is rejected at the declaration, an intersection becomes never

Click the diagram to see it full size.

For describing object shapes, both can do the same things:

  • optional fields (?) and readonly,
  • generics (ApiResponse<T> from Part 10),
  • extension: interface B extends A or type B = A & { ... },
  • being used by a class with implements.

People often think the last one is interface-only. It is not:

TS
type PembayaranGateway = { tagih(jumlah: number): Promise<string> };   // tagih = charge
interface Notifikasi { kirim(ke: string, pesan: string): Promise<void> } // kirim = send

class Midtrans implements PembayaranGateway {
  async tagih(jumlah: number) { return `INV-${jumlah}`; }
}
class EmailNotifikasi implements Notifikasi {
  async kirim(ke: string, pesan: string) { console.log(`email ke ${ke}: ${pesan}`); }
}
TEXT
email ke [email protected]: tiket terbit
INV-150000

Both compile. So for most everyday code, the choice really is about consistency. The real differences are in the next three places.


2. Only type Can Do This

TS
type Status = 'pending' | 'paid' | 'failed';            // union
type Koordinat = [lat: number, lng: number];            // tuple
type Opsional<T> = { [K in keyof T]?: T[K] };           // mapped type
type IsiPromise<T> = T extends Promise<infer U> ? U : T; // conditional type
type Id = string;                                        // primitive alias

All the tools from earlier parts, such as the Pembayaran discriminated union (Part 9), ApiResponse<T>, and combined utilities like Partial<Pick<...>> (Part 10), must use type. There is no choice here.


3. Only interface Can Do This: Declaration Merging

Interfaces with the same name merge (question 1). It sounds like a quirk, but it is exactly how you add fields to another library's types. The most common example: attaching the logged-in user to Express's Request.

TS
import type { Request } from 'express';

declare global {
  namespace Express {
    interface Request {
      pengguna?: { id: string; peran: 'admin' | 'pembeli' };
    }
  }
}

function hanyaAdmin(req: Request): boolean {      // admin only
  return req.pengguna?.peran === 'admin'; // TypeScript knows this field thanks to declaration merging
}
TEXT
true

Our interface Request merges with the interface Request from @types/express. From then on, req.pengguna is recognised in every handler, with no as anywhere. The same pattern adds variables to ProcessEnv or properties to Window.

The dark side: merging can also happen by accident. Two files that both declare interface Config in the global scope get merged silently. Inside a module (a file with an import or export), each interface has its own scope, so the risk is small. Watch out for declarations in the global scope.


4. Conflicts When Extending: extends vs &

This is the difference people miss most, and the one behind the opening bug.

TS
interface Dasar { id: string }
interface Turunan extends Dasar { id: number }   // rejected here

type DasarT = { id: string };
type TurunanT = DasarT & { id: number };          // accepted... with id typed as never
const x: TurunanT = { id: 1 };                     // only caught here
TEXT
bentrok.ts(2,11): error TS2430: Interface 'Turunan' incorrectly extends interface 'Dasar'.
  Types of property 'id' are incompatible.
    Type 'number' is not assignable to type 'string'.
bentrok.ts(6,23): error TS2322: Type 'number' is not assignable to type 'never'.

(Dasar = base, Turunan = derived, bentrok = clash.)

  • extends checks that the child fits the parent, and rejects it on the declaration line with a clear message.
  • & combines without checking. The conflict becomes never, and the error shows up far from the cause, with a confusing never in it.

If you are extending object shapes and want conflicts caught as early as possible, interface ... extends is safer.


5. So Which One?

The non-negotiable rules:

NeedUse
Unions, tuples, mapped, conditional, primitive aliasestype (the only option)
Adding fields to a library's type (Request, ProcessEnv)interface (the only option)
Extending object shapes with conflicts caught at the declarationinterface ... extends

For everything else, which is plain object shapes, both are fine. The TypeScript Handbook itself says the choice is mostly personal preference, and offers a heuristic: use interface until you need a feature only type has.

What matters more than the choice is consistency, and a machine should enforce it, not review comments. typescript-eslint has a consistent-type-definitions rule you can set to type or interface. Set it once, and the 30-comment argument from the opening never needs to happen again.


Summary

  • For object shapes, they are almost the same: optional fields, readonly, generics, implements.
  • Only type: unions, tuples, mapped types, conditional types, primitive aliases.
  • Only interface: declaration merging, used to augment libraries such as Express.Request. Watch for accidental merging in the global scope.
  • extends checks conflicts at the declaration. & quietly produces never.
  • The rest is consistency: pick one and lock it in with consistent-type-definitions.

Closing & What's Next

The id: never bug from the opening would be caught on its declaration line with interface ... extends. And the 30-comment argument is settled with one line of ESLint config.

This also closes the TypeScript section of the series. The last two parts return to the backend: making operations safe to repeat (idempotency), then translating every error in one place.

Grab your coffee, see you in the next part!

ShareLinkedInXWhatsApp

Written by Muhammad Fari Madyan

Senior Backend Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

Work with me
← part 10Generics and Utility Typespart 12 →Idempotency

Muhammad Fari Madyan

Senior Backend Engineer building real-time, high-concurrency systems that hold up in production. Co-founder of LampungDev. Based in Bandar Lampung, Indonesia (UTC+7), working remote.

Work

Case studiesCahTixExam platform, 4 stacksOpen source

© 2026 Muhammad Fari Madyan

Designed and built by Muhammad Fari Madyan