← TypeScript17 / 43
Type Narrowing (typeof, in, instanceof)
Narrowing adalah teknik mempersempit tipe union yang lebih luas ke tipe yang lebih spesifik saat runtime menggunakan typeof atau in.
👀 Contoh dulu
function cetak(val: string | number) {
if (typeof val === "string") {
console.log(val.toUpperCase());
}
}
cetak("hello");Hasilnya: HELLO
💡 Narrowing membuka akses ke method spesifik tipe tersebut.
📝 Sekarang giliranmu
Tulis pengondisian if (typeof val === 'number') di dalam fungsi.
Preview