TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
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 regardingtry...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.
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 asunknown, 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.
Master TypeScript with Deep Grasping Methodology!Learn More





