Web Analytics

Type Guards

Intermediate~20 min

Type guards are runtime checks that narrow types, allowing TypeScript to understand what type a value is within a specific code block.

Built-in Type Guards

Output
Click Run to execute your code
Type Guard Syntax: Use value is Type as return type for custom type guard functions

Types of Type Guards

Type Guard Use Case Example
typeof Primitives typeof x === "string"
instanceof Classes x instanceof Date
in Properties "name" in obj
Custom Complex types isUser(x)

Custom Type Guards

interface User {
    userName: string;
    email: string;
}

function isUser(obj: any): obj is User {
    return obj && 
           typeof obj.userName === "string" &&
           typeof obj.email === "string";
}

function process(data: unknown) {
    if (isUser(data)) {
        console.log(data.userName);  // ✓ TypeScript knows it's User
    }
}

Common Mistakes

1. Forgetting 'is' in Return Type

// ✗ Wrong - returns boolean, doesn't narrow type
function isString(value: unknown): boolean {
    return typeof value === "string";
}

// ✓ Correct - narrows type
function isString(value: unknown): value is string {
    return typeof value === "string";
}

2. Incomplete Type Checks

// ✗ Unsafe - doesn't check all properties
function isUser(obj: any): obj is User {
    return obj.userName !== undefined;
}

// ✓ Safe - checks all required properties
function isUser(obj: any): obj is User {
    return obj && 
           typeof obj.userName === "string" &&
           typeof obj.email === "string";
}
Best Practice: Use type guards to safely work with union types and unknown values.

Summary

  • Type guards narrow types at runtime
  • Use typeof, instanceof, in operators
  • Custom guards use value is Type syntax
  • Essential for working with union types