Skip to content

Type predicates fail to remove subclasses from unions for assumeTrue=false. #10254

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

Closed
sandersn opened this issue Aug 10, 2016 · 2 comments
Closed
Assignees

Comments

@sandersn
Copy link
Member

@ahejlsberg you probably already know about this one but I thought I'd confirm:

interface Error {
    e
}
declare function isError(value: any): value is Error;
class CustomError extends Error { }
function narrowTest(value: number | CustomError) {
    if(isError(value)) {
        let result: CustomError = value;
    }
    else {
        let result: number = value; // error!
    }
}

Expected: narrowing to number in the else branch.
Actual: No narrowing: value: CustomError | number in the else branch, causing an error.

I found this in lodash on DefinitelyTyped.

@ahejlsberg
Copy link
Member

ahejlsberg commented Aug 10, 2016

This is an effect of #10216. The issue we face here is that Error and CustomError are structurally identical from the type system's point of view, yet at runtime a CustomError is an instance of Error, but not the other way around. The implementation currently makes the assumption that when two distinct types are structurally identical, neither is an instance of the other. We could look into "cheating" and check whether one extends the other, even though technically that isn't part of the type. Maybe we just need to get over that.

@sandersn
Copy link
Member Author

Hm. We certainly treat structurally identical things badly in a number of other places, so it's already a definite anti-pattern.

I should probably just update lodash's DefinitelyTyped tests, and maybe the Typescript FAQ.

@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