Type Guard Utility
April 18, 2025
Type guards in TypeScript help you narrow down the type of a variable, especially when working with values of type unknown or any. This improves type safety and allows for better code suggestions from your editor.
Here's a basic example of a type guard for strings:
export function isString(value: unknown): value is string {
return typeof value === 'string';
}
How It Works
- The return type
value is stringis a special TypeScript syntax called a type predicate. - It allows TypeScript to narrow the type inside a conditional block if the function returns
true.
Example Usage
function printLength(val: unknown) {
if (isString(val)) {
console.log("Length:", val.length); // TypeScript now knows val is a string
} else {
console.log("Not a string.");
}
}
Why Use Type Guards?
- Prevents runtime errors by ensuring the type before accessing properties.
- Reduces the need for type assertions (
as), which can be unsafe. - Enables safer handling of dynamic data, such as API responses or form inputs.
- Works great in libraries or utility-heavy codebases that handle generic data.
More Advanced Guards
You can write guards for more complex types, such as custom interfaces or objects.
type User = {
id: number;
name: string;
};
export function isUser(value: unknown): value is User {
return (
typeof value === 'object' &&
value !== null &&
'id' in value &&
'name' in value
);
}
function handleUser(input: unknown) {
if (isUser(input)) {
console.log(input.name); // Safe access
} else {
console.log("Invalid user object.");
}
}
Bonus: Combine with Type Narrowing
Type guards can be composed with Array.prototype.filter:
const values: unknown[] = ["hello", 42, "world"];
const stringsOnly = values.filter(isString); // string[]
TypeScript now knows stringsOnly is a list of strings thanks to your type guard.
Type guards are a core part of writing safe, scalable TypeScript code — and mastering them gives you confidence when dealing with unknown data.