Microsoft/TypeScript

Control flow analysis for dependent parameters only works when checking against literals

Open

#55,766 创建于 2023年9月17日

在 GitHub 查看
 (2 评论) (2 反应) (0 负责人)TypeScript (6,726 fork)batch import
Domain: check: Control FlowHelp WantedPossible Improvement

仓库指标

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

描述

🔎 Search Terms

narrow, parameters, typeof

🕗 Version & Regression Information

It never worked for typeof / asserts checks since the feature introduction in https://github.com/microsoft/TypeScript/pull/47190; it's been mentioned here:

https://github.com/microsoft/TypeScript/pull/47190#issuecomment-1041216006

⏯ Playground Link

https://www.typescriptlang.org/play?#code/MYewdgzgLgBAZmAMgSygUwE4EMA2AuGACgDpSsMBzCAgbQAMs6AaGMAVwFsAjTAXRgA+Mel2YxoGZGAq8AlDAC8APhgA3EMgAmiolhZd5ymAG8AUDBjI4uxQoUwARFgfyzFi6EggcaYjhAUhAYA3ObuAPTh7tHuAHoA-GEAvqYppp7Q8GAAghAQmFAEJGSU1MIMYuzcfILloiwSUjKGKupaOoR6MAaKKm6W1oTIENmdsq5hHuAQ3r7+gSGTMJExMQnJqenTsAgAKgCeAA5oIHBFpMTkVLRVPBgstzVCNI3SDVCS0nK9ahra9p19C0TGErEQoEcTtYsLZ7A5HhgXCDohlZn4AkFZKFoitVnFEhYUmk4GwwMAoMhwJYRoRVLgCKSANZgEAAdzAsgIdJw1JgFWRMAwaCgbAwYBgHzYaFCKSAA

💻 Code

const fnLiteral: (...args: [`a`, number] | [`b`, string]) => void = (a, b) => {
  if (a === "a") {
    console.log(b);
    //          ^? number
  }
}

const fnAssert: (...args: [`a`, number] | [`b`, string]) => void = (a, b) => {
  if (isA(a)) {
    console.log(b);
    //          ^? number | string
  }
}
const fnTypeof: (...args: [number, number] | [string, string]) => void = (a, b) => {
  if (typeof a === "number") {
    console.log(b);
    //          ^? number | string
  }
}

function isA(val: unknown): val is `a` {
  return true;
}

🙁 Actual behavior

Both fnAssert and fnTypeof are unable to get TS to recognize b as its narrowed type (number). Only if a is checked against a literal does the narrowing works.

🙂 Expected behavior

The b parameter should be narrowed to number.

Additional information about the issue

No response

贡献者指南