Type Guards
typeof, instanceof, in, user-defined predicates (x is T), and assertion functions
Skills taught: ts.typeof-guard, ts.instanceof-guard, ts.in-guard, ts.type-predicate, ts.assertion-function
Built-in type guards
// typeof guard — primitives
function format(x: string | number | boolean): string {
if (typeof x === 'string') return x.trim().toUpperCase();
if (typeof x === 'number') return x.toFixed(2);
return x ? 'YES' : 'NO';
}
console.log(format(' hello ')); // HELLO
console.log(format(3.14159)); // 3.14
console.log(format(true)); // YES
// instanceof guard — class instances
class ApiError extends Error {
constructor(public code: number, message: string) {
super(message);
}
}
class NetworkError extends Error {
constructor(public url: string, message: string) {
super(message);
}
}
function handleError(err: Error): string {
if (err instanceof ApiError) {
return `API error ${err.code}: ${err.message}`;
}
if (err instanceof NetworkError) {
return `Network error at ${err.url}: ${err.message}`;
}
return `Unknown error: ${err.message}`;
}
console.log(handleError(new ApiError(404, 'Not found')));
console.log(handleError(new NetworkError('/api', 'Timeout')));
// in guard — property check
interface Cat { meow(): string; }
interface Dog { bark(): string; }
function makeNoise(pet: Cat | Dog): string {
if ('meow' in pet) return pet.meow();
return pet.bark();
}
console.log(makeNoise({ meow: () => 'Meoow!' }));
User-defined type predicates
interface User {
id: number;
name: string;
email: string;
}
// Type predicate: returns x is User
function isUser(x: unknown): x is User {
return (
typeof x === 'object' &&
x !== null &&
'id' in x && typeof (x as any).id === 'number' &&
'name' in x && typeof (x as any).name === 'string' &&
'email' in x && typeof (x as any).email === 'string'
);
}
// Now TypeScript knows the type after the guard
const fromApi: unknown = { id: 1, name: 'Alice', email: 'alice@ex.com' };
if (isUser(fromApi)) {
console.log(fromApi.name.toUpperCase()); // TypeScript knows: string
console.log(fromApi.email);
}
// Works with array.filter too!
const items: unknown[] = [
{ id: 1, name: 'Alice', email: 'alice@ex.com' },
'not a user',
42,
{ id: 2, name: 'Bob', email: 'bob@ex.com' },
];
const users: User[] = items.filter(isUser); // User[], not unknown[]!
console.log(users.map(u => u.name));
// Assertion function — throws if condition not met
function assertUser(x: unknown): asserts x is User {
if (!isUser(x)) throw new Error(`Expected User, got ${JSON.stringify(x)}`);
}
const data: unknown = { id: 3, name: 'Charlie', email: 'c@ex.com' };
assertUser(data);
// After assertUser, TypeScript knows data is User:
console.log(data.name);
Frequently Asked Questions
Can I write a wrong type predicate? Does TypeScript catch it?
Yes, you can write a lying predicate — TypeScript doesn't verify that your predicate actually checks the right thing. function isString(x: unknown): x is string { return true } would compile. TypeScript trusts you. This is intentional: some runtime checks are too complex for the type system to verify. The responsibility for correctness is yours. Use libraries like zod or io-ts for validated type narrowing.