TS18046

'error' is of type 'unknown'.

Broken Code ❌

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:

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();