Skip to content

Incorrect union type inferring when properties match #32050

Closed
@minht11

Description

@minht11

TypeScript Version: 3.4.4 and typescript@3.6.0-dev.20190623
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

Activity

jcalz

jcalz commented on Jun 24, 2019

@jcalz
Contributor

Duplicate of #12184, I think.

fatcerberus

fatcerberus commented on Jun 24, 2019

@fatcerberus
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

typescript-bot commented on Jun 26, 2019

@typescript-bot
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

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @jcalz@fatcerberus@ahejlsberg@minht11@typescript-bot

        Issue actions

          Incorrect union type inferring when properties match · Issue #32050 · microsoft/TypeScript