Microsoft/TypeScript

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

Open

#51,661 opened on Nov 28, 2022

View on GitHub
 (3 comments) (0 reactions) (0 assignees)TypeScript (48,455 stars) (6,726 forks)batch import
BugDomain: This-TypingHelp Wanted

Description

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.

Contributor guide