Lesson 15 of 15

Type Guards

Type Guards

A type guard is a function that returns a boolean and narrows the type of a value inside conditional blocks. Use the is keyword in the return type:

function isString(val: unknown): val is string {
    return typeof val === "string";
}

function print(val: unknown): void {
    if (isString(val)) {
        console.log("String: " + val.toUpperCase());
    } else {
        console.log("Not a string");
    }
}

print("hello");  // String: HELLO
print(42);       // Not a string

instanceof Guards

Use instanceof to narrow class types:

class Dog {
    bark(): string { return "woof"; }
}

class Cat {
    meow(): string { return "meow"; }
}

function speak(animal: Dog | Cat): string {
    if (animal instanceof Dog) {
        return animal.bark();
    }
    return animal.meow();
}

Your Task

Write function isNumber(val: unknown): val is number that checks if a value is a number. Then write function double(val: unknown): string that returns "Double: " + (val * 2) if val is a number, or "Not a number" otherwise.

TypeScript loading...
Loading...
Click "Run" to execute your code.