Microsoft/TypeScript

Extra check in expression cause invalid type narrowing

Open

#47.346 aberto em 7 de jan. de 2022

Ver no GitHub
 (3 comments) (1 reaction) (0 assignees)TypeScript (6.726 forks)batch import
BugDomain: check: Control FlowHelp Wanted

Métricas do repositório

Stars
 (48.455 stars)
Métricas de merge de PR
 (Mesclagem média 6d 17h) (9 fundiu PRs em 30d)

Description

Bug Report

Invalid type narrowing seems to bleed out of expressions that includes "useless" checks, such as :

  • checking the existence of a property marked as required
  • using optional chaining when the variable is never null

🔎 Search Terms

  • invalid type narrowing
  • extra condition narrowing

🕗 Version & Regression Information

Tested in 4.4.4, 4.5.4 and 4.6.0-dev.20220107
This seems to be the behavior in every version I tried, and I didn't find any relevant point if the FAQ

⏯ Playground Link

Playground link with relevant code

💻 Code

type A = { a: string };
type B = { a: string; b: string };

// With useless `'a' in x`
declare const value1: A | B;
'a' in value1 && 'b' in value1 && value1.b;
'a' in value1 && 'b' in value1 && value1.b; // Error

// With useless optionnal chaining
declare const value2: A | B;
'b' in value2 && value2?.b;
'b' in value2 && value2.b; // Error

🙁 Actual behavior

In both case, we get the error Property 'b' does not exist on type 'never'.(2339)
The variable is narrowed to A after the first expression, which cause the next one to fail.

🙂 Expected behavior

No type narrowing should occur outside of the expressions.

Guia do colaborador