Type narrowing adalah proses mempersempit tipe berdasarkan kondisi:
typeof guard:
function proses(input: string | number) {
if (typeof input === "string") {
return input.toUpperCase(); // TS tahu input = string
}
return input * 2; // TS tahu input = number
}
Truthiness narrowing:
function sapa(nama?: string) {
if (nama) {
return `Halo, ${nama}`; // nama pasti string (bukan undefined)
}
return "Halo, anonim";
}
in operator:
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function move(animal: Fish | Bird) {
if ("swim" in animal) animal.swim(); // Fish
else animal.fly(); // Bird
}
instanceof:
function logDate(x: Date | string) {
if (x instanceof Date) console.log(x.toISOString());
else console.log(x);
}
Type Predicate (custom type guard):
Kalau 4 cara di atas belum cukup, kamu bisa bikin type guard sendiri pakai is. TypeScript bakal percaya pada return value-mu untuk mempersempit tipe.
function isString(nilai: unknown): nilai is string {
return typeof nilai === "string";
}
function proses(data: unknown) {
if (isString(data)) {
// Di sini TS tahu data = string
console.log(data.toUpperCase());
}
}
nilai is string artinya: "kalau fungsi ini return true, anggap nilai bertipe string." Pola ini sering dipakai untuk memvalidasi data dari API atau input user.