Microsoft/TypeScript

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

Open

#51,661 建立於 2022年11月28日

在 GitHub 查看
 (3 留言) (0 反應) (0 負責人)TypeScript (6,726 fork)batch import
BugDomain: This-TypingHelp Wanted

倉庫指標

Star
 (48,455 star)
PR 合併指標
 (平均合併 6天 17小時) (30 天內合併 9 個 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.

貢獻者指南