SyntaxStudy
Sign Up
Home TypeScript Reference Type Guards / narrowing

Type Guards / narrowing

class

Type guards narrow the type within a conditional block, making TypeScript aware of the specific type.

Syntax

if (typeof x === "string") if (x instanceof Date)

Example

javascript
function processInput(input: string | number) {
    if (typeof input === 'string') {
        return input.toUpperCase(); // string methods safe here
    } else {
        return input.toFixed(2);   // number methods safe here
    }
}

// instanceof guard
function format(date: Date | string): string {
    if (date instanceof Date) {
        return date.toISOString();
    }
    return date;
}

// Custom type guard
function isUser(obj: unknown): obj is User {
    return typeof obj === 'object' && obj !== null && 'id' in obj;
}