Rafael Munitić Rafael Munitić - 3 months ago 10
TypeScript Question

How to define a function that checks if the parameter is string in TypeScript 2.0

Say I have a function that checks if a parameter is string defined like this :

function isString(value: any): boolean {
return typeof value === 'string' || value instanceof String;
}


Now when I use this function with typescript 2.0 control flow analysis I would expect the following to work :

function foo(param: string|Foo) {
if(isString(param)) {
// param is not narrowed to string here
} else {
// param is not narrowed to Foo here
}
}


Is there a different way I could define isString that would make the example if statement narrow the type of param correctly ?

Answer

Typescript has Type Guards to help with this.

You can have a user defined guard:

function isString(value: any): value is string {
    return typeof value === 'string' || value instanceof String;
}

function foo(param: string | Foo) {
    if (isString(param)) {
        // param is string
    } else {
        // param is Foo
    }
}

But in your case you can just use typeof:

function foo(param: string | Foo) {
    if (typeof param === "string") {
        // param is string
    } else {
        // param is Foo
    }
}

If Foo is a class then you can also use instanceof:

function foo(param: string | Foo) {
    if (param instanceof Foo) {
        // param is Foo
    } else {
        // param is string
    }
}
Comments