TS18046

error TS18046: ‘error‘ is of type ‘unknown‘.

Broken Code ❌

1
2
3
4
5
6
7
8
9
async function test() {
try {
await Promise.reject(new Error('This is a test'));
} catch (error: unknown) {
console.error(error.message);
}
}

test();

Fixed Code ✔️

If you set the useUnknownInCatchVariables option to true in your tsconfig.json file, you may encounter the TS18046 error.

Enabling the useUnknownInCatchVariables feature causes the error within a catch clause to be treated as the unknown type instead of any. As a result, you will need to incorporate a type guard or an assertion function to access properties on an object of type unknown:

1
2
3
4
5
6
7
8
9
10
11
async function test() {
try {
await Promise.reject(new Error('This is a test'));
} catch (error: unknown) {
if (error instanceof Error) {
console.error(error.message);
}
}
}

test();