Category: Next.js, React and TypeScript

TypeScript TS18046: variable error has an unknown type in catch

Read this guide in Polish

Catch(error) code does not allow you to read error.message even though you see Error in the console. JavaScript allows you to throw any value, so TypeScript does not assume that the captured object is an instance of Error.

How to identify the source of the problem

Check all catch locations and whether external libraries return other exceptions shapes. Find out what information can enter the log and what are the customer's secrets or data.

Compare the message from the console with the result of the production compilation and the condition after the page has been refreshed.

Repair steps

Use if(error instanceof Error) before accessing the message and prepare a secure message for other values. For failure of the supplier, develop a separate validation of the form of the response and do not reveal the entire payoad to the user.

How to Test Solution

Typecheck works and the message does not display confidential parts of an API error.

Security and restrictions

Don't change the global catch to any, because you lose the validation of an exception.