Fixing Error: Object is of type ‘unknown’ in TypeScript

Object is of type ‘unknown’ Error in TypeScript

A new “unknown” type was introduced in TypeScript 3.0 which is the type-safe counterpart of the “any” type. Why do you get the “Object is of type ‘unknown’” error in TypeScript? Follow the below document, we will explain and give you how to fix it. 

The cause of this error

In TypeScript, when the user accesses the property of an ‘unknown’ value, the system returns the error “Object is of type unknown”. A quick solution to the error is to use type protection to collapse the object’s type before accessing the property.

How to solve “Object is of type ‘unknown’” error in TypeScript?

In TypeScript 4.0, support was added to change the variable type in a catch clause from ‘any’ to ‘unknown’. 

For example code:

try {
    // ...
} 
catch(err) {
    // We have to verify "err" is an
    // error before using it as one.
    if (err instanceof Error) {
        console.log(err.message);
    }
}

For each variable, Javascript can assign any value, but TypeScript will not return exactly what the error is, because it still does not support declaring the error type.

With earlier versions, when declaring ‘err’ in the catch clause, ‘err’ will be interpreted as ‘any’ by default. As such, you will be allowed to freely access any properties you want. However, with version 4.0, TypeScript has changed in the type assignment for the catch clause, it can be ‘any’ or ‘unknown’. You can see the example below:

try {
    // ...
} 
catch(err) {
    err.stack;
}

// Explicit behavior with unknown
try {
    // ...
} 
catch(err: unknown) {
    err.stack;
    if (err instanceof SyntaxError) {
        err.stack;
    }
}

`err` cannot be used until the system determines what type it is. To better understand you can follow in the example:unknown-and-never.

To set “false” of “useUnknownInCatchVariabls”, open tsconfig.json file and add the below code:

"compilerOptions": {
 	"useUnknownInCatchVariables": false
}

If you set “false” in “useUnknownInCatchVariables”, the variable has error will be classified as “any”.

Summary

We can try to contact a property value that is a “unknown” type when an “Object is of type unknown” error occurs. Use type protection to narrow down an object’s type before accessing a property to solve this error. Thank you for reading!

Maybe you are interested:

Leave a Reply

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