Microsoft/TypeScript

Parentheses in nullish coalescing chains impacts type narrowing

Open

#44,988 创建于 2021年7月12日

在 GitHub 查看
 (1 评论) (0 反应) (0 负责人)TypeScript (6,726 fork)batch import
BugDomain: check: Control FlowHelp Wanted

仓库指标

Star
 (48,455 star)
PR 合并指标
 (平均合并 6天 17小时) (30 天内合并 9 个 PR)

描述

Bug Report

🔎 Search Terms

nullish coalescing chain parentheses type narrowing prettier

🕗 Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about nullish coalescing. Note that at the time of writing, 4.3.5 was the latest stable release.

⏯ Playground Link

Playground link with relevant code

💻 Code

type T =
  | { a: string; b: string }
  | { a: string; b?: undefined }
  | { a?: undefined; b: string };

const getResult1 = (value1: string | undefined, value2: T): string => {
  return value1 ?? value2.a ?? value2.b;
};

const getResult2 = (value1: string | undefined, value2: T): string => {
  return value1 ?? (value2.a ?? value2.b);
};

🙁 Actual behavior

  • getResult1 throws a type error, as TypeScript incorrectly infers that value2.b has a type of string | undefined.
  • getResult2 does not throw a type error, as TypeScript correctly infers that value2.b has a type of string.

🙂 Expected behavior

The existence and placement of parentheses in nullish coalescing chains should not impact type narrowing, as to my knowledge (and prettier, as it automatically removes the parentheses seen in getResult2), x ?? y ?? z and x ?? (y ?? z) actually behave the same at runtime.

贡献者指南