Microsoft/TypeScript

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

Open

#51,661 opened on 2022幎11月28日

GitHub で芋る
 (3 comments) (0 reactions) (0 assignees)TypeScript (6,726 forks)batch import
BugDomain: This-TypingHelp Wanted

Repository metrics

Stars
 (48,455 stars)
PR merge metrics
 (平均マヌゞ 6d 17h) (30d で 9 merged PRs)

説明

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.

コントリビュヌタヌガむド