Type Narrowing and Guards
TypeScript narrows types after checks: typeof, instanceof, in, equality and truthiness. A custom type guard returns value is Type. Discriminated unions use a shared tag property.
Example
type Shape = { kind: "circle"; r: number } | { kind: "rect"; w: number; h: number };
function area(s: Shape) {
switch (s.kind) {
case "circle": return Math.PI * s.r ** 2;
case "rect": return s.w * s.h;
}
}
console.log(area({ kind: "rect", w: 2, h: 3 }).toFixed(1));
function isString(x: unknown): x is string { return typeof x === "string"; }
console.log(isString("a"), isString(1));Result
6.0 true false
Exercise
Return type of a type guard.
function f(x: unknown): x string
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.