Skip to main content
The try...catch statement is a control flow construct used to handle runtime exceptions. It consists of a try block containing code that may throw an exception, a catch block that executes if an exception is thrown, and an optional finally block that executes unconditionally after the try and catch blocks have resolved.

TypeScript Catch Variable Typing

In TypeScript, the most critical distinction regarding try...catch is the typing of the catch clause variable. Because JavaScript permits throwing any value (including strings, numbers, objects, or null), TypeScript enforces strict rules on how the caught exception is typed. 1. Explicit Type Annotations are Invalid TypeScript does not allow explicit type annotations on the catch variable. Attempting to define the error type directly results in a compiler error.
2. The unknown Type Default As of TypeScript 4.4, if the useUnknownInCatchVariables compiler option is enabled (which is the default under strict mode), the catch variable is implicitly typed as unknown. Prior to 4.4, or if the flag is disabled, it defaults to any. You can explicitly annotate the variable as any or unknown, but unknown is the recommended and safest approach.

Type Narrowing in Catch Blocks

Because the caught error is typed as unknown, you cannot directly access properties like error.message or error.code. You must perform type narrowing using type guards (instanceof, typeof, or custom type predicate functions) to safely interact with the exception payload.

Asserting Custom Error Types

If you are working with custom error classes and are certain of the exception type being thrown, you can use type assertions (as) after catching the error. However, this bypasses TypeScript’s safety checks and should be used cautiously.
Tired of Poor TypeScript Skills? Fix That With Deep Grasping!Learn More