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

Node.js & TypeScript Backend Part 10: Generics and Utility Types — ApiResponse<T>, keyof, Pick vs Omit & Record

Part ten of a Node.js & TypeScript series that opens with a quiz: generics as types passed as parameters, ApiResponse<T> for every endpoint, extends and keyof constraints, Partial, Pick, Omit, Record and friends, and three traps such as Omit accepting a typo so passwordHash gets sent out.

Muhammad Fari Madyan

· 9 min read

Baca dalam Bahasa Indonesia →

Opening: The passwordHash That Got Sent Out

The team has a Pengguna (user) type with a passwordHash field. For the profile endpoint, someone writes a "safe" type:

TS
type PenggunaAman = Omit<Pengguna, 'pasword'>;

It compiles. It passes review. Two months later someone opens the /profile response in DevTools and finds passwordHash sitting there.

One s went missing from 'password', and TypeScript said nothing. Why? And why does Pick with the same typo get rejected straight away?

This part is about two tools that let you reuse types without writing them over and over: generics and utility types. Plus a few sharp corners you need to know about.


Warm-Up Quiz: Do You Still Remember?

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

Question 1. Given function pertama<T>(xs: T[]): T | undefined, what is T when you call pertama([1, 'a'])?

  • A. number
  • B. string | number
  • C. unknown
Show the answer to question 1

B: string | number. (pertama = first.) TypeScript infers T from the array's contents. The result is string | number | undefined, so .toFixed() is rejected until you narrow it (Part 9).

Question 2. Does this compile?

TS
type Pengguna = { id: string; nama: string; passwordHash: string };
type A = Omit<Pengguna, 'pasword'>;   // typo
  • A. Yes, and A still has passwordHash
  • B. No, a compile error
Show the answer to question 2

A. Omit accepts any key, including ones that do not exist on the original type. Nothing is removed, and there is no warning. That is the opening story.

Question 3. What about Pick<Pengguna, 'pasword'>?

  • A. It compiles, giving an empty object
  • B. A compile error
Show the answer to question 3

B. error TS2344: Type '"pasword"' does not satisfy the constraint 'keyof Pengguna'. Pick requires the key to actually exist.

Question 4. Does this compile?

TS
type Status = 'pending' | 'paid' | 'failed';
const label: Record<Status, string> = { pending: 'Menunggu', paid: 'Lunas' };
  • A. Yes
  • B. No, failed is missing
Show the answer to question 4

B. error TS2741: Property 'failed' is missing. Record<Status, string> requires every status to have a label. When a new status is added, every label map that was not updated turns red.

Question 5. Partial<Event>, where Event = { id: string; lokasi: { kota: string } }. Is { lokasi: {} } accepted?

  • A. Yes, everything becomes optional
  • B. No, Partial only applies to the first level
Show the answer to question 5

B. (lokasi = location, kota = city.) Property 'kota' is missing in type '{}'. Partial makes lokasi optional, but if you do fill in lokasi, its contents must still be complete.

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


1. Generics: Types as Parameters

A function takes values as parameters. A generic takes types as parameters.

Picture a storage box with an empty label slot. The box is the same, and the label is filled in when you use it: "box of Events", "box of Orders". If you followed the Java series on this blog, this is the same idea as Kotak<T> in Part 20 of the Java series.

The most useful backend example: one response shape for every endpoint.

TS
// One API response shape for every endpoint (see Part 9 and Part 13).
type ApiResponse<T> =
  | { ok: true; data: T }
  | { ok: false; error: { code: string; message: string } };

function sukses<T>(data: T): ApiResponse<T> {          // sukses = success
  return { ok: true, data };
}
function gagal(code: string, message: string): ApiResponse<never> {   // gagal = failure
  return { ok: false, error: { code, message } };
}

type Event = { id: string; nama: string; kuota: number };

function cariEvent(id: string): ApiResponse<Event> {
  if (id !== 'EV-1') return gagal('EVENT_TIDAK_DITEMUKAN', `Event ${id} tidak ditemukan`);
  return sukses({ id, nama: 'Konser Lampung', kuota: 500 });
}

const hasil = cariEvent('EV-1');
if (hasil.ok) {
  console.log(hasil.data.kuota);        // data is an Event
} else {
  console.log(hasil.error.code);
}
TEXT
500

Three things are happening:

  • ApiResponse<T> is written once. ApiResponse<Event>, ApiResponse<Order> and so on come for free. If the error shape changes, you change one place.
  • The shape is a discriminated union labelled by ok (Part 9), so hasil.data is only available after if (hasil.ok).
  • gagal returns ApiResponse<never>. Because never fits any type, the result of gagal(...) can be returned from a function that promises ApiResponse<Event> or ApiResponse<Order>.

2. Constraints with extends, and keyof

A generic with no constraint accepts anything. Often we need a condition: "anything, as long as it has an id".

TS
// A generic with a constraint: T must have an id.
function indeksBerdasarId<T extends { id: string }>(items: T[]): Record<string, T> {
  return Object.fromEntries(items.map((item) => [item.id, item]));
}
const peta = indeksBerdasarId([{ id: 'EV-1', nama: 'Konser', kuota: 500 }]);
console.log(peta['EV-1']?.nama);
TEXT
Konser

(indeksBerdasarId = index by id, peta = map.) keyof T is the union of every field name in T. Combined with a generic, we can write a function whose return type follows the field you ask for:

TS
function ambil<T, K extends keyof T>(obj: T, kunci: K): T[K] {   // ambil = get, kunci = key
  return obj[kunci];
}
const kuota = ambil({ id: 'EV-1', nama: 'Konser', kuota: 500 }, 'kuota'); // number
console.log(kuota.toFixed(0));

And a typo is caught immediately:

TS
ambil({ id: 'EV-1', kuota: 500 }, 'kouta');
TEXT
error TS2345: Argument of type '"kouta"' is not assignable to parameter of type '"id" | "kuota"'.

The K extends keyof T pattern is exactly what makes Pick reject 'pasword' in question 3.


3. Utility Types: Derive, Don't Rewrite

From one Pengguna type: Pick takes id and nama for a public profile, Omit drops passwordHash, Partial makes fields optional for a PATCH, and Record maps every status to a label

Click the diagram to see it full size.

TypeScript ships ready-made generics for transforming existing types. Everything derives from one source, so when Pengguna changes, the derived types change with it.

TS
type Pengguna = {
  id: string;
  nama: string;
  email: string;
  passwordHash: string;
  dibuatPada: Date;
};

type ProfilPublik = Pick<Pengguna, 'id' | 'nama'>;            // public profile
type PenggunaAman = Omit<Pengguna, 'passwordHash'>;           // safe user
type UbahPengguna = Partial<Pick<Pengguna, 'nama' | 'email'>>; // update user

type Status = 'pending' | 'paid' | 'failed';
const labelStatus: Record<Status, string> = {
  pending: 'Menunggu',
  paid: 'Lunas',
  failed: 'Gagal',
};
UtilityMeaningBackend use
Partial<T>Every field optionalA PATCH body
Required<T>Every field requiredConfig after defaults are applied
Pick<T, K>Keep certain fieldsPublic profiles, list summaries
Omit<T, K>Drop certain fieldsA type without secret data
Record<K, V>An object with keys K and values VA label per status
Readonly<T>Fields cannot be changedConfig, constants
ReturnType<F>A function's return typeA factory's type without rewriting it
Awaited<T>What a Promise resolves toThe result of an async function

Look at UbahPengguna: utilities can be combined. "Take nama and email, then make them optional" is exactly the body for PATCH /users/:id. Users cannot change id or passwordHash through that endpoint, and TypeScript enforces it. You still need runtime validation (Part 8), and zod schemas have matching methods: .pick(), .omit(), .partial().


4. Three Traps

Trap 1: Omit does not check its keys

This is the opening story. Omit<T, K> is defined with K extends keyof any, meaning any key is accepted. The result:

TS
type A = Omit<Pengguna, 'pasword'>;   // typo, still compiles
const bocor: A = { id: 'u1', nama: 'Fari', passwordHash: 'rahasia' }; // A still has passwordHash

No error. Two ways to stay safe:

  1. For data that leaves the server, it is safer to choose what may go out (Pick) than to remove what may not (Omit). A new secret field will never slip out by accident.

  2. If you still want Omit, make a strict version:

    TS
    type OmitKetat<T, K extends keyof T> = Omit<T, K>;   // ketat = strict
    

    Now OmitKetat<Pengguna, 'pasword'> is rejected, just like Pick.

And remember, types remove nothing at runtime. If the object you send still contains passwordHash, that field goes out, whatever its type says. Pick the fields explicitly when you build the response, or use a schema that drops unknown fields.

Trap 2: Partial is only one level deep

Question 5. Partial does not reach into nested objects. If you need a deep version, write one with a recursive mapped type, but think first: a deeply nested PATCH body is often clearer split into more specific endpoints.

Trap 3: a generic that is really an as in disguise

TS
function parse<T>(json: string): T {
  return JSON.parse(json);
}
const user = parse<Pengguna>(text); // looks safe, but nothing checks it

T here is used for nothing but the return type. That is the same as JSON.parse(text) as Pengguna (Part 7), just tidier to look at. If a generic only appears in the return type, be suspicious. The honest version takes a schema, parse(text, UserSchema), and T is inferred from that schema.


Summary

  • A generic = a type as a parameter. ApiResponse<T> is written once and used by every endpoint.
  • T extends ... adds a condition. K extends keyof T guarantees the key exists, and T[K] follows the field's type.
  • Utility types: Partial, Required, Pick, Omit, Record, Readonly, ReturnType, Awaited. Derive from one source.
  • Record<Status, string> forces every status to have a label.
  • Traps: Omit accepts typos (use Pick or OmitKetat), Partial is one level deep, and a generic that only appears in the return type is an as in disguise.

Closing & What's Next

The passwordHash from the opening should never have been able to leave: Pick<Pengguna, 'id' | 'nama'> chooses what may go out, and even the smallest typo is rejected.

In the next part we answer a question that starts debates in code review: when to use type, when to use interface, and whether the difference really matters.

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 9Narrowing and Discriminated Unionspart 11 →type vs interface

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