TS2571
error TS2571: Object is of type ‘unknown’.
Broken Code ❌
If you use third-party libraries then it can happen that TypeScript cannot infer all return types. In such a case a return type can be unknown
which makes it impossible to access its properties from TypeScript. In the following example such case is constructed by assigning unknown
to an exemplary constant:
1 |
|
Fixed Code ✔️
To solve the problem of accessing properties from an unknown object, we have to define the type of the object which we want to access:
1 |
|
Broken Code ❌
1 |
|
Fixed Code ✔️
If your variable is of type unknown
, then you can use a type guard to narrow the type of your variable. If you want to be sure that you have an object at hand, you can use the typeof
type guard:
1 |
|
Alternative
You may also get the error “Object is of type ‘unknown’” when catching errors. In this case you have to type the error in your catch clause.