Microsoft/TypeScript

Type-asserting function call on variable initialized using `this` causes false implicit-any in VSCode

开放

#51,661 创建于 2022年11月28日

 (3 条评论) (0 个反应) (0 位负责人)TypeScript (13,395 个派生)batch import
BugDomain: This-TypingHelp Wanted

仓库指标

星标
 (108,860 个星标)
PR 合并指标
 (PR 指标待抓取)

描述

Bug Report

🔎 Search Terms

asserts, this, vscode, language server, implicit any

🕗 Version & Regression Information

  • This changed between versions 4.6 and 4.7
  • This is also a problem on Nightly (5.0.0-dev.20221128)

This issue seems to be specific to VSCode's TS support - I have not been able to reproduce it in either the Playground nor the Bug Workbench. tsc itself accepts this code with no issues.

💻 Code

const assertExists: <T extends number>(actual: T | null | undefined) => asserts actual is T = () => {};

type Value = { n: number | undefined };
const callThisFunc = (f: (this: Value) => void): void => {
  f.call({ n: 42 });
};

callThisFunc(function() {
  const maybeN = this.n;
  assertExists(maybeN);
});

🙁 Actual behavior

Sometimes, usually when freshly loading this code, this works normally. If you edit the function body passed to callThisFunc in any way, even stuff like adding superfluous semicolons, maybeN will become red-underlined and complain about implicit-any on hover. Further appearances of maybeN in the function are also treated as any.

This error does not happen if you do not call assertExists, nor does it happen if you give this an explicit type, like so:

callThisFunc(function(this: Value) {
  const maybeN = this.n;
  assertExists(maybeN);
});

🙂 Expected behavior

This should not display any errors in VSCode, and the assertExists call should correctly narrow the type to number.

贡献者指南