microsoft / microsoft/TypeScript

Narrowing from `typeof x !== 'object'` incorrectly excludes functions.

未关闭
#44,855 3 条评论 3 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

In Discussion Suggestion
主要语言
Go
星标
111k
派生
14.4k
平均合并
1 天 19 小时
30 天内合并 PR
117

描述

Bug Report

🔎 Search Terms

typeof object function narrow, type narrowing

🕗 Version & Regression Information

Present in all recent versions from at least 3.3.3333 through the current nightly 4.4.0-dev.20210701

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about "typeof" and "narrow"
⏯ Playground Link

Playground link

💻 Code
let x!: string|object; // |Function;
if (1 < 2) x = () => 1;

if (typeof x !== 'object') {
  useString(x); // should fail, but doesn't
}

declare function useString(s: string): void;
🙁 Actual behavior

The type narrowing for typeof x !== 'object' pruned the entire |object branch from x's type union, but typeof can return either "object" or "function" for values of type object, so this is overzealous. This causes x inside the conditional to be incorrectly narrowed to just string when we can clearly see from the earlier line that it's been assigned a function, which is incorrectly passed to useString with no complaint.

🙂 Expected behavior

Excluding "object" from typeof x should not remove |object from its type, in the same way that it doesn't narrow unknown any further. This would cause the appropriate type error from passing a function to useString.

Note that if an explicit |Function branch is added to to x's type union then the narrowing proceeds as expected.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从链接的 TypeScript Playground 和提供的 narrowing 示例开始,然后跟踪 typeof x !== "object" 的类型 narrowing 逻辑。当赋值给 x 的函数不会被 narrowing 排除,并且将 x 传递给 useString 会产生预期的类型错误时,修复就完成了;请根据所述版本验证行为。

由索引模型根据 Issue 内容生成。

评估

技术栈
typescript
领域
compilers
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
描述清楚
新手友好度
45/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。