4 min read
Basic Error Handling with Types
try/catch works exactly like JavaScript — but note that a caught
error's type is unknown by default in strict TypeScript, not any,
so you must narrow it before accessing its properties.
try {
JSON.parse("not valid json");
} catch (error) {
if (error instanceof Error) {
console.log(error.message);
}
}
Common mistakes
- Accessing
error.messagedirectly without aninstanceof Errorcheck first — sinceerror's type isunknown, TypeScript won't let you assume it has a.messageproperty.