Skip to content

Incorrect type narrowing on generic type above 4.9.5 #53773

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
zheeeng opened this issue Apr 14, 2023 · 0 comments Β· Fixed by #53794
Closed

Incorrect type narrowing on generic type above 4.9.5 #53773

zheeeng opened this issue Apr 14, 2023 · 0 comments Β· Fixed by #53794
Assignees
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue

Comments

@zheeeng
Copy link

zheeeng commented Apr 14, 2023

Bug Report

πŸ”Ž Search Terms

Generic type narrowing

πŸ•— Version & Regression Information

  • This changed between versions 4.8.4 and 4.9.5

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.0.4#code/GYVwdgxgLglg9mABFApgZygHgCqJQD1TABM1EBDMATwG0BdRAH0QCUUI4AnYzDTmMAHMANBWoA+cQAo4AIwBWALkTYAlIgDeAWABQifYhjBEUgIKdO5KgDoYac5aoyF6xswDkAGxRCoAC3dDJDl5dW09A30QgG5dfQB6eMQAPQB+OIMAXzxPNBRNDMiYjMSU9Ij9TN0qnV1QSFgEZHQoACYcPEIfUjFaBmY2Dm5eKH4hUUoqSWclFTDCw2MzCytbexWnENV5ioNiiNK0heyUXPzwyKiFWIOko92amqA

πŸ’» Code

function test<T extends any[] | Record<string, any>>(obj: T) {
    if (Array.isArray(obj) || 'length' in obj) {
      obj;
  // ^? (parameter) obj: T extends any[] | Record<string, any>
    } else {
      obj;
  // ^? (parameter) obj: never
    }
}

function test2<T extends any[] | Record<string, any>>(obj: T) {
    if (Array.isArray(obj)) {
      obj;
  // ^? (parameter) obj: T & any[]
    } else {
      obj;
  // ^? (parameter) obj: T extends any[] | Record<string, any>
    }
}

πŸ™ Actual behavior

In the else branch of the test function, obj is inferred as never type.

πŸ™‚ Expected behavior

In the else branch of the test function, obj should be inferred as T extends any[] | Record<string, any> type.

@RyanCavanaugh RyanCavanaugh added Bug A bug in TypeScript Help Wanted You can do this labels Apr 14, 2023
@RyanCavanaugh RyanCavanaugh added this to the Backlog milestone Apr 14, 2023
@ahejlsberg ahejlsberg self-assigned this Apr 15, 2023
@ahejlsberg ahejlsberg removed the Help Wanted You can do this label Apr 15, 2023
@ahejlsberg ahejlsberg modified the milestones: Backlog, TypeScript 5.1.0 Apr 15, 2023
@typescript-bot typescript-bot added Fix Available A PR has been opened for this issue labels Apr 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript Fix Available A PR has been opened for this issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants