How to Fix ‘error’ is of type ‘unknown’ in Typescript

Issue

When writing a try and catch block in TypeScript within Visual Studio Code, it’s common to encounter the error message “‘error’ is of type ‘unknown’” within the catch block.

Screenshot:

The image above showcases a basic example. When you hover over the word “error,” indicated by the red underline, a tooltip message appears

“‘error’ is of type ‘unknown’.ts(18046) var error: unknown”.

Solution Attempt

Simply assigning the type “Error” to the parameter “error” doesn’t resolve the issue.

Screenshot:

it gives another error message when hovering over the word “Error”, which is underlined in red:

‘Catch clause variable type annotation must be ‘any’ or ‘unknown’ if specified.ts(1196) interface Error’.

Solution

Add an if statement to check if error is an instance of Error.

const divide = (dividend: number, divider: number) => {
    if (divider === 0) {
        throw new Error('Divider must not be zero!')
    }
    return dividend / divider
}

try {
    divide(5, 0)
} catch (error) {
    if (error instanceof Error) {
        console.log(error.message)
    }
}
JavaScript

It resolves the editor’s complaint! Hurray!

Reference Resources

Leave a Reply

Your email address will not be published. Required fields are marked *