TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

improper declared type cause narrow type not work when its computed type is not union.

Open ShuiRuTian opened this issue 5 years ago • 7 comments

TypeScript Version: 4.0

Search Terms:

Code

interface A {
    type:'A'
}

interface B {
    type:'B'
}

function assert(x:any) :asserts x is A|B{

}

function foo(x: any): any {
    x;  // any
    assert(x);
    x;  // A | B
    if (x.type === 'A') {
        return x;
    }
    x;  // B
    if (x.type === 'B') {
        return x;
    }
    x;  // B, but should be never.
//  ^?
}

Expected behavior: the last x should be never.

Actual behavior: still B.

Playground Link: https://www.typescriptlang.org/play/index.html?ts=4.0.0-dev.20200615&ssl=1&ssc=1&pln=25&pc=2#code/JYOwLgpgTgZghgYwgAgIIG8BQyfLATwAcIAuAclTMwF9NNRJZEUAhLXPI0slq2zGAFcQCMMAD2IZHADOM6GAAUADxJwQ+AJTI1chTOTLkwA6gA+bOvyEixk5DHHiVJaRs2v1+ZO1zKA3DgA9EFu+Ni4svJQSsqa-hE4AcGhqMhmyCyJxjDIKgB0BMTIALxlyBRk2r4cOFAQYIJQUgHZtBzJyCGZ2cC5BUUoZSUVvNXZHPWNzYYJHO1+gV2hWdRAA

Related Issues:

ShuiRuTian avatar Jun 17 '20 17:06 ShuiRuTian

The reason is isMatchingReferenceDiscriminant function return false at the second time. Declared type is no use here.

#38839 Add this link, for I meet similar problem in the fix.

ShuiRuTian avatar Jun 17 '20 17:06 ShuiRuTian

( I sneakily edited the issue body to be a twoslash compiler repro to test the bot )

orta avatar Jul 17 '20 13:07 orta

@typescript-bot run repros

orta avatar Jul 17 '20 14:07 orta

Heya @orta, I've started to run the code sample repros for you. Here's the link to my best guess at the log.

typescript-bot avatar Jul 17 '20 14:07 typescript-bot

Think I've got the bugs down, @typescript-bot run repros

orta avatar Jul 17 '20 19:07 orta

Heya @orta, I've started to run the code sample repros for you. Here's the link to my best guess at the log.

typescript-bot avatar Jul 17 '20 19:07 typescript-bot

:wave: Hi, I'm the Repro bot. I can help narrow down and track compiler bugs across releases! This comment reflects the current state of the repro in the issue body running against the nightly TypeScript.


Issue body code block by @ShuiRuTian

:warning: Assertions:

  • (parameter) x: B
Historical Information
Version Reproduction Outputs
4.2.2, 4.3.2, 4.4.2, 4.5.2, 4.6.2

:warning: Assertions:

  • (parameter) x: B

typescript-bot avatar Apr 13 '22 23:04 typescript-bot