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

May be a bug in type guards #26463

Closed
AlexStacker opened this issue Aug 15, 2018 · 2 comments
Closed

May be a bug in type guards #26463

AlexStacker opened this issue Aug 15, 2018 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@AlexStacker
Copy link

AlexStacker commented Aug 15, 2018

TypeScript Version: 3.0.1

Search Terms:
type guards

Code
This is the sample code. I am going to print an http request value in the click event and output msg based on the returned code, but it is not successful.

interface StatusOK {
  code: 1;
  msg: string;
}

interface StatusNotOK {
  code: -1;
}

type Status = StatusOK | StatusNotOK;

let rst: Status = {code: 1, msg: 'OK'}

if (rst.code === 1) {
  console.log(rst.msg); // ok

  let element = document.getElementById('code');
  if(element) {
    element.addEventListener('click', function(){
        console.log(rst.msg); // Property 'msg' does not exist on type 'Status'.
                              // Property 'msg' does not exist on type 'StatusNotOK'.
    })
  }
}

I look forward to prompt the correct type

Expected behavior:
The results are the type of output an error.

Actual behavior:
Property 'msg' does not exist on type 'Status'.
Property 'msg' does not exist on type 'StatusNotOK'.

Playground Link:
https://agentcooper.github.io/typescript-play/#code/JYOwLgpgTgZghgYwgAgMpjmArgZwPIDSyA3gFDLIID2AJhAFzICMA3OcgLY4DmjOYUUNzYBfUqVCRYiFOky4AclTCES7anUYBaVqTGkwATwAOsjNhzIAvGnO5VAH1vycSlQTakANhDDIo-IxyFtYkGgzMADScPIwA5IRx+sAwyAAUAWAAdOHWVjZMAJRqFNQgOFQ+WV5U3Bn8WVzchZ4UPn4QPhwQ4KE0VAhY3eBZ3L4Aol09YABChgCSNGlx4XEt7ClpnRDDYMVkFBTbu1lwNDTjAG7TADLA-D3QywhewAgA1nHRMFggCGDAKggNKFA6HcFlCpVGp1TKNHjrcEiQrsMQiIA

Related Issues:
#2214

@mattmccutchen
Copy link
Contributor

Working as intended; see #8541 for more information.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Aug 15, 2018
@RyanCavanaugh
Copy link
Member

See also #9998 for extended discussion of types of guarded expressions in callbacks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants