Type guards allow you to inspect values at runtime and inform the TypeScript compiler of a narrower type within a conditional block.
typeof: Checks primitives (string, number, boolean, symbol, bigint, function).instanceof: Checks class instances.in operator: Checks for property existence on objects.arg is TargetType.// Custom Type Predicate Function (arg is TargetType)
interface Dog {
kind: "dog";
bark: () => void;
}
interface Cat {
kind: "cat";
meow: () => void;
}
type Pet = Dog | Cat;
// Custom Type Guard
function isDog(pet: Pet): pet is Dog {
return (pet as Dog).bark !== undefined;
}
function handlePetSound(pet: Pet): void {
if (isDog(pet)) {
// TypeScript narrows pet to Dog inside this block!
pet.bark();
} else {
// TypeScript narrows pet to Cat inside this block!
pet.meow();
}
}
const myDog: Dog = { kind: "dog", bark: () => console.log("Woof!") };
handlePetSound(myDog);
arg is Type for Custom Guards: Standard boolean return types do not trigger compiler type narrowing.in and typeof: Use built-in JavaScript operators inside guards before resorting to custom assertion functions.Write a custom type guard isString(val: unknown): val is string using typeof val === "string".
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With