Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type guards fail with external typeof check #13773

Closed
jednano opened this issue Jan 31, 2017 · 2 comments
Closed

Type guards fail with external typeof check #13773

jednano opened this issue Jan 31, 2017 · 2 comments

Comments

@jednano
Copy link
Contributor

jednano commented Jan 31, 2017

Related to #2388

TypeScript Version: 2.1.5 (Playground)

Code

function foo(x: number | string) {
    if (isString(x)) {
        x.substr(1); // <-- Error
    }
}

function isString(x: any) {
    return typeof x === 'string';
}

Expected behavior:

No errors.

Actual behavior:

Error: Property 'substr' does not exist on type 'string | number'.
       Property 'substr' does not exist on type 'number'.

Value Proposition:

This is a common thing to do with external libraries (e.g., Lodash):

//_.isString
interface LoDashStatic {
    /**
     * Checks if value is classified as a String primitive or object.
     *
     * @param value The value to check.
     * @return Returns true if value is correctly classified, else false.
     */
    isString(value?: any): value is string;
}

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/lodash/index.d.ts#L12586-L12595
https://lodash.com/docs/4.17.4#isString

@blakeembrey
Copy link
Contributor

blakeembrey commented Jan 31, 2017

It works fine for me, you just didn't annotate the function:

function foo(x: number | string) {
    if (isString(x)) {
        x.substr(1); // <-- Error
    }
}

function isString(x: any): x is string {
    return typeof x === 'string';
}

Or is the issue about automatically inferring type guards based on the function? In that case, I imagine it's a little more complicated.

@jednano
Copy link
Contributor Author

jednano commented Jan 31, 2017

Thanks @blakeembrey!

@jednano jednano closed this as completed Jan 31, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants