A simple utility function to narrow unknown types in TypeScript.
export function isString(value: unknown): value is string {
return typeof value === 'string';
}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';
}
value is string is a special TypeScript syntax called a type predicate.true.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.");
}
}
as), which can be unsafe.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.");
}
}
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.