Skip to content

Type Guards & Narrowing

TypeScript

Narrow types at runtime with type guards: typeof, instanceof, in, custom.

Official Site
01

Overview

Type guards narrow union types. typeof for primitives. instanceof for classes. in for property presence. Custom: x is Type predicate. Discriminated unions with literal types. Exhaustiveness checking with never.

bash
function process(x:string|number){
  if(typeof x==="string") return x.toUpperCase();
  return x.toFixed(2);
}
// Custom guard
function isUser(x:any):x is User{return x&&typeof x.id==="number";}
// Discriminated union
type Shape={kind:"circle";r:number}|{kind:"square";s:number};
function area(s:Shape){
  switch(s.kind){
    case "circle":return Math.PI*s.r**2;
    case "square":return s.s**2;
  }
}
02

Best Practices

Use discriminated unions for variant types. Custom guards with is predicate. Exhaustiveness check with never. Avoid any (use unknown). Use assertion functions (asserts x is T). Prefer in over instanceof for structural checks.)

Ready to try Type Guards & Narrowing?

Visit the official site for the latest version and full documentation.

Visit Type Guards & Narrowing