Custom type guards for runtime type checking
Quick Answer
A TypeScript type guard is a function with a `value is Type` return annotation that lets the compiler narrow the type inside an if-block after a runtime check.
1function isString(value: unknown): value is string {
2 return typeof value === 'string';
3}
4
5function isNumber(value: unknown): value is number {
6 return typeof value === 'number' && !isNaN(value);
7}
8
9function isObject(value: unknown): value is Record<string, unknown> {
10 return typeof value === 'object' && value !== null && !Array.isArray(value);
11}TypeScript type guards are functions that return a type predicate (value is Type) to narrow union types at runtime. They bridge the gap between TypeScript's static analysis and real-world dynamic data such as API responses, user inputs, and JSON payloads.
A type assertion (`as Type`) is an unsafe compile-time override with no runtime check. A type guard performs a real runtime check whose result the compiler trusts — it is always safer.
Yes. You can write `function isArrayOf<T>(arr: unknown, guard: (x: unknown) => x is T): arr is T[]` to create reusable generic guards.
This free typescript code snippet for type guards is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement type guards quickly and correctly.
All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.