1

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 ?

2 Answers 2

3

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

The return type needs to use the custom type guard syntax for this to work:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.