Sub topic 11
Unknown catch variables and alwaysStrict
This chapter covers two flags that "strict": true turns on and that are easy to overlook: useUnknownInCatchVariables and alwaysStrict. It assumes you can read a tsconfig.json. It also assumes you know that strict is an umbrella option that switches on a group of flags, as the earlier chapters on strict and noImplicitAny explain. You should know basic try/catch and instanceof in JavaScript.
What useUnknownInCatchVariables does
JavaScript lets you throw any value. throw "oops", throw 42, and throw { code: 7 } are all legal. Because of this, the compiler cannot know what a catch clause receives.
Before TypeScript 4.4, the catch variable had the type any. You could write error.message without any check, and a thrown string would crash that line at runtime. The flag useUnknownInCatchVariables changes the type to unknown. You must narrow an unknown value before using it.
try {
JSON.parse("{");
} catch (error) {
if (error instanceof Error) {
console.log(error.message);
}
}With the flag on, error.message outside the if is a compile error: 'error' is of type 'unknown'. Inside the if, instanceof narrows error to Error, so the access is allowed.
The flag was added in TypeScript 4.4 and is part of strict from that version on. If you upgrade TypeScript on a project that already has "strict": true, new errors can appear in old catch blocks.
Where the flag applies and where it does not
The flag affects only the variable in a catch (name) clause. It does not change other places where a failure value appears.
| Location | Type of the error value | Changed by the flag? |
|---|---|---|
| `catch (e)` clause | `unknown` with the flag, `any` without | Yes |
| `promise.catch((e) => ...)` callback | `any` | No |
| `catch (e: unknown)` with an annotation | `unknown` | No, you chose it |
| `catch (e: any)` with an annotation | `any` | No, you chose it |
The Promise.catch row catches many teams. The standard library declares the rejection reason as any, so strict mode does not protect you there. If you use async/await with try/catch, you get the protection. If you chain .catch(...), annotate the parameter yourself: .catch((reason: unknown) => ...).
Since TypeScript 4.0, a catch clause may carry an annotation, but only unknown or any. Annotating with Error is rejected, because the compiler cannot guarantee what was thrown.
Narrowing patterns
A single instanceof Error check is often enough. Production code usually needs a few more cases, so it helps to write one helper and reuse it.
function toMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
}
if (typeof error === "string") {
return error;
}
return String(error);
}
try {
throw "something broke";
} catch (error) {
console.log(toMessage(error));
}This prints something broke. A thrown Error gives its message, a thrown string is passed through, and anything else is converted with String.
You can narrow to your own error classes the same way. Each instanceof check gives you access to that class's fields.
class HttpError extends Error {
constructor(
message: string,
public readonly status: number,
) {
super(message);
this.name = "HttpError";
}
}
function handle(error: unknown): string {
if (error instanceof HttpError) {
return `HTTP ${error.status}: ${error.message}`;
}
if (error instanceof Error) {
return `Error: ${error.message}`;
}
return "Unknown failure";
}
try {
throw new HttpError("Not found", 404);
} catch (error) {
console.log(handle(error));
}Check the most specific class first. HttpError is also an Error, so reversing the two if statements would make the first branch catch everything.
Common errors and gotchas
- Cross-realm errors. An
Errorcreated in another realm, such as avmcontext or an iframe, has a differentErrorconstructor.instanceof Errorreturnsfalsefor it. If you handle such values, add a structural check, for exampletypeof error === "object" && error !== null && "message" in error. - Old compile targets. When you extend
Errorwith a target of ES5 or lower, the prototype chain breaks.instanceof HttpErrorthen returnsfalse. Withtarget: "ES2022"as in this tutorial's examples, classes are emitted natively and the problem does not occur. - Reaching for
any. Writingcatch (error: any)everywhere removes the protection. Use it only at a spot where you have a real reason, and leave a comment. - Rethrowing.
throw errorwith anunknownvalue is allowed. You can narrow, handle the cases you know, and rethrow the rest.
Turning the flag off
To keep the rest of strict but opt out of this one flag, set it to false:
{
"compilerOptions": {
"strict": true,
"useUnknownInCatchVariables": false
}
}This is useful during a migration: you adopt the other checks first and come back to the catch blocks later. A later chapter on moving to strict mode describes that approach. Explicit flags override the umbrella regardless of their order in the file.
What alwaysStrict does
JavaScript has a "strict mode" that removes some unsafe behavior. For example, assigning to an undeclared variable throws an error instead of creating a global. The alwaysStrict flag does two things.
- It makes the compiler parse your source files as strict-mode code. Constructs that strict mode forbids become compile errors, such as
withstatements, legacy octal literals like010, and duplicate parameter names. - It emits a
"use strict";directive at the top of every generated JavaScript file.
Files that are ES modules are already strict by definition, so the directive adds nothing for them in practice. The flag matters most for scripts and for CommonJS output. A file with no import or export is a script, and without the flag it would run in sloppy mode.
You can set the flag alone without strict:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"alwaysStrict": true
}
}With module: "NodeNext", whether a file is treated as an ES module or as CommonJS depends on the nearest package.json "type" field and on the file extension.
Checking the effect
To see which of these flags are active, print the resolved configuration:
npx tsc --showConfigWith "strict": true, the output lists strict but not each flag it implies. To confirm the behavior, write a catch block that reads error.message without narrowing, then run npx tsc --noEmit. You should get the 'error' is of type 'unknown' message. Then set useUnknownInCatchVariables to false and run it again. The error disappears.
Exercise
A project has "strict": true. A function contains promise.catch((e) => console.log(e.message)) and compiles without errors, while an equivalent try { await promise } catch (e) { console.log(e.message) } fails to compile. Why do the two differ, and how do you make the first one safe?
Show answer
The flag useUnknownInCatchVariables applies only to catch clauses. The callback of Promise.catch declares its reason parameter as any in the standard library, so e.message type-checks. Make the first one safe by annotating the parameter as unknown, for example .catch((e: unknown) => console.log(toMessage(e))), and narrowing it before use.
Exercise
What two things does alwaysStrict do, and why does it have little visible effect on a file that contains an import statement?
Show answer
It parses the source as strict-mode JavaScript, which turns constructs such as with and legacy octal literals into errors, and it emits "use strict" at the top of each output file. A file with an import statement is an ES module, and modules are always strict, so the directive and the stricter parsing add nothing new for it.