0
TypeScript · Advanced TypeScript
New technique
Narrowing, all the ways
A master smith reads the metal before striking. TypeScript reads your checks the same way.
TypeScript follows your ifs and returns (control flow analysis) and narrows a union in each branch. Each kind of check narrows a different kind of type.
Watch out: typeof null is "object", so check for null separately. And the in operator only works on objects, so prove something is a non-null object before you ask what's in it.
function describe(x: string | number[] | Date | null) {
if (x === null) return "nothing"; // x: null
if (typeof x === "string") return x; // x: string
if (Array.isArray(x)) return x.length; // x: number[]
return x.toISOString(); // x: Date
}x instanceof Datenarrows to objects made by a class."swim" in petnarrows to the union members that have aswimproperty.- Under
strict, the variable incatch (err)isunknown: JavaScript can throw anything, even a string. Checkerr instanceof Errorbefore readingerr.message.