Skip to content

TS doesn't narrow arrays in a union #45301

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
SavvyShah opened this issue Aug 3, 2021 · 4 comments
Closed

TS doesn't narrow arrays in a union #45301

SavvyShah opened this issue Aug 3, 2021 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@SavvyShah
Copy link

SavvyShah commented Aug 3, 2021

Bug Report

πŸ”Ž Search Terms

narrowing array union

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

type Point = {
  x: number;
  y:number;
}
type Pair = [number, number]

type Coords = Point | Pair

function print1(a: Coords): number{
  if("x" in a){
    return a.x;
  } else{
    return a[0];
  }
}

function print2(a: Pair[] | Point[]): void{
  if("x" in a[0]){
    console.log(a[0].x)
  } else{
    console.log(a[0][0])
  }
}

πŸ™ Actual behavior

It should correctly narrow array type as Point[] instead of Point[] | Pair[] in print2().

πŸ™‚ Expected behavior

It should have done it because I don't have a mixed type where if a[0] is Point then a[1] could be Pair which is what I mean when I do Point[ ] | Pair[ ]

Also this SO link could help to explain.

@DanielRosenwasser
Copy link
Member

DanielRosenwasser commented Aug 3, 2021

This works correctly if you use TypeScript nightly (or 4.4 beta) and use --exactOptionalPropertyTypes. misread the issue

@DanielRosenwasser DanielRosenwasser added Working as Intended The behavior described is the intended behavior; this is not a bug and removed Working as Intended The behavior described is the intended behavior; this is not a bug labels Aug 3, 2021
@DanielRosenwasser
Copy link
Member

Sorry, misread the issue - maybe I'm missing something but everything seems correctly narrowed in the playground.

@fatcerberus
Copy link

Maybe OP was expecting a itself to be narrowed rather than just a[0]? TypeScript doesn't narrow the containing object when you perform a check on one of its properties except in specific situations. Thus why we have discriminated unions.

If I'm right, this is effectively a duplicate of #42384.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Aug 4, 2021
@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