Skip to content

Incorrect type narrowing on generic type above 4.9.5Β #53773

Closed
@zheeeng

Description

@zheeeng

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.

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions