type guard
A run time check, such as typeof x === "string" or a custom function, that the compiler uses to narrow a type.
In more detail
Built-in guards include typeof, instanceof and in. A custom type guard is a function returning a type predicate such as val is Record<string, unknown>, which packages a check for reuse.
Related terms
- type narrowing — The compiler refining a broad type to a more specific one inside a block, after a check proves which case applies.
- type predicate — A return type written param is Type, which tells the compiler that when the function returns true, the argument has that type.
- typeof — A keyword that asks for the type of a value, both in JavaScript at run time and in TypeScript types.
- instanceof — The JavaScript operator that checks whether an object was created by a given class, by walking its prototype chain.
Taught in
- any Versus unknown: Defensive Typing In Practice — Production TypeScript
- Typeof Guards, Truthiness And Equality Narrowing — Production TypeScript