Catch variables typed as unknown is not correctly limited by type guards when used in functions

Bug Report

🔎 Search Terms

  • catch variables
  • unknown
  • type guards
  • functions

🕗 Version & Regression Information

This is a bug specific for version 4 onwards, when catch variables can be typed as unknown.

Playground Link

https://www.typescriptlang.org/play?ts=4.4.2#code/C4JwngBA3gvhDGBDY8AWEAUBTAlNAUBBAJYBmmWJAdgM7CJXxYD25AoiCMyHlIUZjwBeAHwQsAOgC2WGjUQBzLAG5+MfDCA

💻 Code

try {} catch (e) {
  if (e instanceof Error) {
    () => e.message;
  }
}

In previous versions of TS that is >= 4:

try {} catch (e: unknown) {
  if (e instanceof Error) {
    () => e.message;
  }
}

🙁 Actual behavior

Does not work: it says e is of type unknown. I expected it to work because e has been type guarded.

🙂 Expected behavior

Should work, just like in the following example:

const fn = (a: string | Error) => {
  if (a instanceof Error) {
    () => a.message
  }
}

Workaround

Currently something like this works.

try {} catch (e) {
  if (e instanceof Error) {
    const message = e.message;
    () => message;
  }
}

1 thought on “Catch variables typed as unknown is not correctly limited by type guards when used in functions

Comments are closed.