Object is of type ‘unknown’ typescript generics

Since this is the first result you get when you google Object is of type 'unknown', I want to post my case. It might help future readers. This is not the answer to OP’s question.

I got this error in the catch block. After debugging for a while I came to know that starting typescript v4.0, catch clause variables have type unknown instead of any.

And according to docs:

unknown is safer than any because it reminds us that we need to
perform some sort of type-checks before operating on our values.

My code looked something like this before v4.0:

try {
  // try something exceptional here
} catch (error) {
  console.log(error.message);
}

And to fix this error, I had to put an additional if check on error variable.

try {
  // try something exceptional here
} catch (error) {
  let errorMessage = "Failed to do something exceptional";
  if (error instanceof Error) {
    errorMessage = error.message;
  }
  console.log(errorMessage);
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)