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

Incorrect union type inferring when properties match #32050

Closed
minht11 opened this issue Jun 23, 2019 · 3 comments
Closed

Incorrect union type inferring when properties match #32050

minht11 opened this issue Jun 23, 2019 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@minht11
Copy link

minht11 commented Jun 23, 2019

TypeScript Version: 3.4.4 and [email protected]
Search Terms:

Code

type someType = {
  name: 'first',
  first: string,
} | {
  name: 'second',
  second: string,
}

function someFunction(arg1: someType, arg2: someType) {
  if (arg1.name === arg2.name) {
    if (arg1.name === 'first') {
      // Here compiler shows an error
      console.log(arg2.first)
    }
  }
}

Expected behavior:
Since arg1 and arg2 have same names property first should also exist on arg2
Actual behavior:
Property 'first' does not exist on type 'someType'.
Property 'first' does not exist on type '{ name: "second"; second: string; }'.ts(2339)
Playground Link:
https://www.typescriptlang.org/play/#src=type%20someType%20%3D%20%7B%0D%0A%20%20name%3A%20'first'%2C%0D%0A%20%20first%3A%20string%2C%0D%0A%7D%20%7C%20%7B%0D%0A%20%20name%3A%20'second'%2C%0D%0A%20%20second%3A%20string%2C%0D%0A%7D%0D%0A%0D%0Afunction%20someFunction(arg1%3A%20someType%2C%20arg2%3A%20someType)%20%7B%0D%0A%20%20if%20(arg1.name%20%3D%3D%3D%20arg2.name)%20%7B%0D%0A%20%20%20%20if%20(arg1.name%20%3D%3D%3D%20'first')%20%7B%0D%0A%20%20%20%20%20%20%2F%2F%20Here%20compiler%20shows%20an%20error%0D%0A%20%20%20%20%20%20console.log(arg2.first)%0D%0A%20%20%20%20%7D%0D%0A%20%20%7D%0D%0A%7D

@jcalz
Copy link
Contributor

jcalz commented Jun 24, 2019

Duplicate of #12184, I think.

@ahejlsberg ahejlsberg added the Duplicate An existing issue was already created label Jun 24, 2019
@fatcerberus
Copy link

if (arg1.name === 'first') {

This can only narrow arg1. TS only narrows variables directly involved in the conditional expression and doesn't track relationships with other variables.

@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

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

5 participants