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:
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?
type Pengguna = { id: string; nama: string; passwordHash: string };
type A = Omit<Pengguna, 'pasword'>; // typo
- A. Yes, and
Astill haspasswordHash - 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?
type Status = 'pending' | 'paid' | 'failed';
const label: Record<Status, string> = { pending: 'Menunggu', paid: 'Lunas' };
- A. Yes
- B. No,
failedis 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,
Partialonly 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.
// 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);
}
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), sohasil.datais only available afterif (hasil.ok). gagalreturnsApiResponse<never>. Becauseneverfits any type, the result ofgagal(...)can be returned from a function that promisesApiResponse<Event>orApiResponse<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".
// 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);
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:
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:
ambil({ id: 'EV-1', kuota: 500 }, 'kouta');
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
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.
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',
};
| Utility | Meaning | Backend use |
|---|---|---|
Partial<T> | Every field optional | A PATCH body |
Required<T> | Every field required | Config after defaults are applied |
Pick<T, K> | Keep certain fields | Public profiles, list summaries |
Omit<T, K> | Drop certain fields | A type without secret data |
Record<K, V> | An object with keys K and values V | A label per status |
Readonly<T> | Fields cannot be changed | Config, constants |
ReturnType<F> | A function's return type | A factory's type without rewriting it |
Awaited<T> | What a Promise resolves to | The 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:
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:
-
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. -
If you still want
Omit, make a strict version:TStype OmitKetat<T, K extends keyof T> = Omit<T, K>; // ketat = strictNow
OmitKetat<Pengguna, 'pasword'>is rejected, just likePick.
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
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 Tguarantees the key exists, andT[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:
Omitaccepts typos (usePickorOmitKetat),Partialis one level deep, and a generic that only appears in the return type is anasin 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!

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.

