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

Node.js & TypeScript Backend Part 9: Narrowing and Discriminated Unions — typeof, in, Type Guards & the never Guard

Part nine of a Node.js & TypeScript series that opens with a quiz: narrowing with typeof, the truthiness trap with a 0 discount, typeof null, instanceof and in, type guards and assertion functions, a pending, paid, failed discriminated union with a switch and a never guard, and z.discriminatedUnion.

Muhammad Fari Madyan

· 9 min read

Baca dalam Bahasa Indonesia →

Opening: The Status Nobody Invited

Picture a payment system with three statuses: pending, paid, failed. One day a refund feature arrives, so the team adds a fourth: refunded.

The build is green. The tests are green. Three weeks later someone notices: the transaction history page prints undefined for every refund, and the finance report counts refunds as payments still waiting.

Nobody forgot to write the refund code. What got forgotten was every other place that checks the payment status.

TypeScript can point at those places for you, on one condition: you model the data correctly. This part is about narrowing and discriminated unions.


Warm-Up Quiz: Do You Still Remember?

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

Question 1. Does this compile?

TS
function format(x: string | number) {
  return x.toFixed(2);
}
  • A. Yes
  • B. No
Show the answer to question 1

B. error TS2339: Property 'toFixed' does not exist on type 'string | number'. As long as x might be a string, you cannot call a number-only method.

Question 2. What does hargaAkhir(100000, 0) return?

TS
function hargaAkhir(harga: number, diskon?: number): number {
  if (diskon) {
    return harga - diskon;
  }
  return harga + 5000; // no discount: add an admin fee
}
  • A. 100000
  • B. 105000
Show the answer to question 2

B: 105000. (hargaAkhir = final price, diskon = discount.) 0 is falsy, so if (diskon) treats a discount of 0 as "no discount". A buyer with a 0 discount gets charged the admin fee.

Question 3. Does this compile?

TS
function namaPembeli(x: { nama: string } | null | string) {
  if (typeof x === 'object') {
    return x.nama;
  }
  return x;
}
  • A. Yes
  • B. No
Show the answer to question 3

B. error TS18047: 'x' is possibly 'null'. In JavaScript, typeof null is 'object'. So inside that if, x can still be null.

Question 4. With the type below, can you read p.metode directly?

TS
type Pembayaran =
  | { status: 'pending'; dibuatPada: Date }
  | { status: 'paid'; dibayarPada: Date; metode: 'qris' | 'va' }
  | { status: 'failed'; alasan: string };

function cetak(p: Pembayaran) {
  console.log(p.metode);
}
  • A. Yes
  • B. No, check p.status === 'paid' first
Show the answer to question 4

B. (Pembayaran = payment, metode = method, alasan = reason.) metode only exists on a paid payment. TypeScript says: Property 'metode' does not exist on type 'Pembayaran'.

Question 5. Section 5 has a switch with a guard, const tidakMungkin: never = p, in its default. If a refunded status is added to the type without a new case, what happens?

  • A. Nothing, until a real refund comes in
  • B. A compile error right on that guard line
Show the answer to question 5

B. Type '{ status: "refunded"; ... }' is not assignable to type 'never'. That is exactly the alarm the team in the opening needed.

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


1. Narrowing: A Type That Gets Smaller in Each Branch

Picture a parcel sorting machine in a warehouse. Parcels come in on one belt: documents, electronics, food. Each sorting gate checks one thing and sends the parcel down the right lane. In the food lane, you are certainly holding food.

TypeScript does the same with your code. It reads if, switch, return and throw, and works out a narrower type in each branch. That is narrowing.

TS
function format(x: string | number) {
  if (typeof x === 'number') {
    return x.toFixed(2);   // here x: number
  }
  return x.trim();         // here x: string
}

There are several sorting gates. Let's go through them.


2. typeof, Truthiness and Equality

typeof

For primitives: 'string', 'number', 'boolean', 'bigint', 'symbol', 'undefined', 'function' and 'object'.

The trap is the last one. typeof null === 'object' is an old JavaScript mistake kept for compatibility. That is question 3. The fix:

TS
if (typeof x === 'object' && x !== null) {
  return x.nama; // safe now
}

Truthiness: watch out for 0 and ''

if (value) filters out every falsy value: undefined, null, false, 0, NaN and ''. For objects that is usually what you want. For numbers and strings, often not.

Here is question 2, run:

TS
console.log(hargaAkhir(100000, 10000));
console.log(hargaAkhir(100000, 0));
console.log(hargaAkhir(100000));
TEXT
90000
105000
105000

A discount of 0 is treated like no discount. The fix: ask what you actually mean.

TS
if (diskon !== undefined) {
  return harga - diskon;
}
TEXT
100000

The same goes for || versus ??. diskon || 10 replaces 0 with 10. diskon ?? 10 only replaces null and undefined.


3. instanceof and in

instanceof for classes, especially errors

TS
class PembayaranGagalError extends Error {        // payment failed error
  constructor(public readonly alasan: string) {
    super(`Pembayaran gagal: ${alasan}`);
    this.name = 'PembayaranGagalError';
  }
}

function tangani(err: unknown): string {          // tangani = handle
  if (err instanceof PembayaranGagalError) return `402 ${err.alasan}`;
  if (err instanceof Error) return `500 ${err.message}`;
  return '500 kesalahan tidak dikenal';            // unknown error
}

Order matters: check the most specific class first. A PembayaranGagalError is also instanceof Error, so if Error is checked first, the first branch is never reached. We will use this pattern again in the part on centralized error handling.

in for object shapes

TS
type Admin = { peran: 'admin'; izin: string[] };
type Pembeli = { peran: 'pembeli'; saldo: number };

function ringkas(u: Admin | Pembeli) {
  if ('izin' in u) return `admin dengan ${u.izin.length} izin`;
  return `pembeli, saldo ${u.saldo}`;
}

(peran = role, izin = permissions, pembeli = buyer, saldo = balance.)

TEXT
402 saldo kurang | 500 kesalahan tidak dikenal
admin dengan 1 izin | pembeli, saldo 5000

4. Type Guards and Assertion Functions

When the check is complicated, wrap it in a function. In Part 7 we wrote the type guard isPesanan(x): x is Pesanan.

Its sibling is the assertion function: instead of returning true or false, it throws when the condition fails. After that line, TypeScript knows the value is safe.

TS
function assertAda<T>(nilai: T | null | undefined, pesan: string): asserts nilai is T {
  if (nilai === null || nilai === undefined) throw new Error(pesan);
}

const pesanan = await cariPesanan(id);           // { id: string } | null
assertAda(pesanan, 'order not found');
console.log(pesanan.id);                         // here the order definitely exists

(assertAda = assert it exists, cariPesanan = find order.) This keeps service code flat: no nested if (!order) { ... } everywhere.


5. Discriminated Unions: One Label, Three Shapes

Three shapes of Pembayaran with a status label: pending has dibuatPada, paid has dibayarPada and metode, failed has alasan. A switch on status unlocks the matching fields, and a default with never catches any status that was forgotten

Click the diagram to see it full size.

Now the most useful tool for backend code. A payment has several states, and each state carries different data:

TS
type Pembayaran =
  | { status: 'pending'; dibuatPada: Date }
  | { status: 'paid'; dibayarPada: Date; metode: 'qris' | 'va' }
  | { status: 'failed'; alasan: string };

(dibuatPada = created at, dibayarPada = paid at.) The status field is the discriminant. Its values are literals ('pending', not just string), so TypeScript can tell the full shape from that label alone.

TS
function labelPembayaran(p: Pembayaran): string {
  switch (p.status) {
    case 'pending':
      return 'Menunggu pembayaran';                  // waiting for payment
    case 'paid':
      return `Lunas via ${p.metode.toUpperCase()}`; // here p definitely has metode
    case 'failed':
      return `Gagal: ${p.alasan}`;
    default: {
      const tidakMungkin: never = p; // guard: fails to compile if a status is not handled
      return tidakMungkin;
    }
  }
}
TEXT
Lunas via QRIS
Gagal: kartu ditolak

The never guard

never is a type with no values at all. If the cases cover every status, nothing is left in default, so p is never and the guard line compiles.

Now add refunded to the type, without touching the switch:

TS
  | { status: 'refunded'; dikembalikanPada: Date };
TEXT
error TS2322: Type '{ status: "refunded"; dikembalikanPada: Date; }' is not assignable to type 'never'.

The compile error appears in every switch that forgot it, with file name and line number. The team in the opening would see that list before merging, not three weeks later.

Why not one object with optional fields?

Compare it with a more "practical" model:

TS
type PembayaranLonggar = { status: string; dibayarPada?: Date; metode?: string; alasan?: string };
const aneh: PembayaranLonggar = { status: 'paid', alasan: 'kartu ditolak' }; // compiles

A payment that is paid but has a failure reason and no payment date. The loose model allows impossible states, and every reader has to guess which fields are filled. A discriminated union makes those impossible states impossible to write.

From request to union: zod

Outside data can be validated straight into a union (continuing from Part 8):

TS
const Pembayaran = z.discriminatedUnion('status', [
  z.object({ status: z.literal('pending'), dibuatPada: z.iso.datetime() }),
  z.object({ status: z.literal('paid'), dibayarPada: z.iso.datetime(), metode: z.enum(['qris', 'va']) }),
  z.object({ status: z.literal('failed'), alasan: z.string() }),
]);
type Pembayaran = z.infer<typeof Pembayaran>;

console.log(Pembayaran.safeParse({ status: 'paid', alasan: 'x' }).error?.issues.map((i) => `${i.path.join('.')}: ${i.message}`));
TEXT
[
  'dibayarPada: Invalid input: expected string, received undefined',
  'metode: Invalid option: expected one of "qris"|"va"'
]

zod reads status: 'paid', then checks against the rules for paid only. Even the error messages are on target.


Summary

  • Narrowing: TypeScript narrows types in every branch of if, switch, return and throw.
  • typeof for primitives. Remember typeof null === 'object', so add x !== null.
  • Truthiness filters out 0 and ''. For numbers and strings, use !== undefined and ??.
  • instanceof for classes (most specific first), in for object shapes.
  • Type guards (x is T) and assertion functions (asserts x is T) for checks you reuse.
  • Discriminated unions with a literal label such as status, plus a switch and a never guard: a forgotten new status becomes a compile error.
  • The right model makes impossible states impossible to write.

Closing & What's Next

The refunded status from the opening can no longer slip through quietly. Every switch that forgets it turns red before the code is merged.

In the next part we look at two tools that save you from writing types like these over and over: generics and utility types such as Partial, Pick, Omit, Record and ApiResponse<T>.

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 8Runtime Validationpart 10 →Generics and Utility Types

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