What does the `is` keyword do in typescript?

See the reference for user-defined type guard functions for more information.

function isString(test: any): test is string{
    return typeof test === "string";
}

function example(foo: any){
    if(isString(foo)){
        console.log("it is a string" + foo);
        console.log(foo.length); // string function
    }
}
example("hello world");

Using the type predicate test is string in the above format (instead of just using boolean for the return type), after isString() is called, if the function returns true, TypeScript will narrow the type to string in any block guarded by a call to the function.
The compiler will think that foo is string in the below-guarded block (and ONLY in the below-guarded block)

{
    console.log("it is a string" + foo);
    console.log(foo.length); // string function
}

A type predicate is just used in compile time. The resulting .js file (runtime) will have no difference because it does not consider the TYPE.

I will illustrate the differences in below four examples.

E.g 1:
the above example code will not have a compile error nor a runtime error.

E.g 2:
the below example code will have a compile error (as well as a runtime error) because TypeScript has narrowed the type to string and checked that toExponential does not belong to string method.

function example(foo: any){
    if(isString(foo)){
        console.log("it is a string" + foo);
        console.log(foo.length);
        console.log(foo.toExponential(2));
    }
}

E.g. 3:
the below example code does not have a compile error but will have a runtime error because TypeScript will ONLY narrow the type to string in the block guarded but not after, therefore foo.toExponential will not create compile error (TypeScript does not think it is a string type). However, in runtime, string does not have the toExponential method, so it will have runtime error.

function example(foo: any){
    if(isString(foo)){
        console.log("it is a string" + foo);
        console.log(foo.length);
    }
    console.log(foo.toExponential(2));
}

E.g. 4:
if we don’t use test is string (type predicate), TypeScript will not narrow the type in the block guarded and the below example code will not have compile error but it will have runtime error.

function isString(test: any): boolean{
    return typeof test === "string";
}
function example(foo: any){
    if(isString(foo)){
        console.log("it is a string" + foo);
        console.log(foo.length);
        console.log(foo.toExponential(2));
    }
}

The conclusion is that test is string (type predicate) is used in compile-time to tell the developers the code will have a chance to have a runtime error. For javascript, the developers will not KNOW the error in compile time. This is the advantage of using TypeScript.

Leave a Comment