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:
const x: unknown = 1337;
console.log(x.toString());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:
const x: number = 1337;
console.log(x.toString());Broken Code ❌
export const hasUsers = (payload: unknown): payload is { users: string[] } => {
return 'users' in payload;
};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:
export const hasUsers = (payload: unknown): payload is { users: string[] } => {
if (payload && typeof payload === 'object') {
return 'users' in payload;
}
return false;
};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.
