Learn
← Previous Next →

Type Guards

8 min Last updated 23 Mar 2026

Type Guards di TypeScript

Type Guards adalah teknik untuk mempersempit tipe data dalam sebuah blok kode. TypeScript akan "tahu" tipe yang lebih spesifik setelah guard berhasil.

typeof Guard

function processInput(input: string | number) {
  if (typeof input === "string") {
    // TypeScript tahu: input adalah string di sini
    return input.toUpperCase();
  } else {
    // TypeScript tahu: input adalah number di sini
    return input * 2;
  }
}

instanceof Guard

class ApiError extends Error {
  constructor(public statusCode: number, message: string) {
    super(message);
  }
}

function handleError(error: Error | ApiError) {
  if (error instanceof ApiError) {
    console.log(`HTTP ${error.statusCode}: ${error.message}`);
  } else {
    console.log(`Error: ${error.message}`);
  }
}

Custom Type Guard (is)

interface Cat { meow(): void; }
interface Dog { bark(): void; }

// Fungsi type guard dengan return type "is"
function isCat(animal: Cat | Dog): animal is Cat {
  return (animal as Cat).meow !== undefined;
}

function makeSound(animal: Cat | Dog) {
  if (isCat(animal)) {
    animal.meow(); // TypeScript tahu ini Cat
  } else {
    animal.bark(); // TypeScript tahu ini Dog
  }
}