Using typeof

suggest change

typeof is used when you need to distinguish between types number, string, boolean, and symbol. Other string constants will not error, but won’t be used to narrow types either.

Unlike instanceof, typeof will work with a variable of any type. In the example below, foo could be typed as number | string without issue.

This code (try it):

function example(foo: any) {
    if (typeof foo === "number") {
        // foo is type number in this block
        console.log(foo + 100);
    }

    if (typeof foo === "string") {
        // fooi is type string in this block
        console.log("not a number: " + foo);
    }
}

example(23);
example("foo");

prints

123
not a number: foo

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents