Skip to content

TS2.9 narrows {}|undefined to never after string checks (regression from 2.8) #25179

Closed
@mprobst

Description

@mprobst

TypeScript Version: 2.9.2

Search Terms: string never undefined jQuery

Code

declare const childSelector: {}|undefined;
declare const elem: HTMLElement;
if (typeof childSelector === 'string') {
  // childSelector is never (bug?)
  const childElement: HTMLElement|null = elem.querySelector(childSelector);
  // childElement is now null
  if (!childElement) {
    throw new Error('...');
  }
  // childElement is now never
  childElement.addEventListener('click', () => 1);
}

Expected behavior:

TypeScript understands that childSelector must be string in the block. This is what TS 2.8 did.

Actual behavior:

TypeScript infers childSelector to be never, then outsmarts the user's type annotation of HTMLElement|null to be just null, then deducts that in the last line, it must be never.

Playground Link: http://www.typescriptlang.org/play/#src=declare%20const%20childSelector%3A%20%7B%7D%7Cundefined%3B%0D%0Adeclare%20const%20elem%3A%20HTMLElement%3B%0D%0Aif%20(typeof%20childSelector%20%3D%3D%3D%20'string')%20%7B%0D%0A%20%20%2F%2F%20childSelector%20is%20never%20(bug%3F)%0D%0A%20%20const%20childElement%3A%20HTMLElement%7Cnull%20%3D%20elem.querySelector(childSelector)%3B%0D%0A%20%20%2F%2F%20childElement%20is%20now%20null%0D%0A%20%20if%20(!childElement)%20%7B%0D%0A%20%20%20%20throw%20new%20Error('...')%3B%0D%0A%20%20%7D%0D%0A%20%20%2F%2F%20childElement%20is%20now%20never%0D%0A%20%20childElement.addEventListener('click'%2C%20()%20%3D%3E%201)%3B%0D%0A%7D

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScript

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions