. Advertisement .
..3..
. Advertisement .
..4..
The unknown type was introduced by TypeScript, which is a type-safe counterpart of ‘any’ type. This type has the main value proposition which refers to that no arbitrary operations are allowed to perform on values of the unknown type. Therefore, the error “Object is of type unknown” will appear when you try to reach or perform any operation on the value of this type. This blog will bring you some methods to solve this problem. Keep on reading!
1. How Does the Error “Object is of Type Unknown” Occur in TypeScript?
You can only assign the value of an unknown type to itself or the any type. Hence, it makes that with the unknown type values, there is no operation considered as a correct type. Moreover, it seems that the default on this type is just like almost permitting nothing. Thus, when you try to conduct arbitrary operations on the unknown type value, it will lead to the error “Object is of type unknown” as the below example:
let value: unknown;
let value1: unknown = value; // OK
let value2: any = value; // OK
let value3: boolean = value; // Error
let value4: number = value; // Error
let value5: string = value; // Error
let value6: object = value; // Error
let value7: any[] = value; // Error
let value8: Function = value; // Error
2. Solve the Error “Object is of Type Unknown” by Narrowing the Type
With the above example, there is no guarantee that the error contained within the catch block is the early error instance. Hence, to avoid any errors of unexpected runtime, TypeScripts set unknown as its type. To solve this, a type guard should be used for narrowing down the object type before reaching a certain property.
function stringifyForLogging(value: unknown): string {
if (typeof value === "function") {
// Within this branch, `value` has type `Function`,
// so we can access the function's `name` property
const functionName = value.name || "(anonymous)";
return `[function ${functionName}]`;
}
if (value instanceof Date) {
// Within this branch, `value` has type `Date`,
// so we can call the `toISOString` method
return value.toISOString();
}
return String(value);
}
To assess whether err is an error object instance, the operator instanceof is used. If yes, the property of the message can be accessed safely because all the messages in error instances are in string type.
Note: If you encountered the error at another place, perhaps you will not provide a generic type. For example, a type might not be passed for the value returning an HTTP request.
Alternatively, to narrow the type unknown, we can also use the custom function of type guard:
/**
* A custom type guard function that determines whether
* `value` is an array that only contains numbers.
*/
function isNumberArray(value: unknown): value is number[] {
return (
Array.isArray(value) && value.every(element => typeof element === "number")
);
}
const unknownValue: unknown = [15, 23, 8, 4, 42, 16];
if (isNumberArray(unknownValue)) {
// Within this branch, `unknownValue` has type `number[]`,
// so we can spread the numbers as arguments to `Math.max`
const max = Math.max(...unknownValue);
console.log(max);
}
3. Solve the Error “Object is of Type Unknown” by Using Type Assertions
In the last section, we have known how typeof, instanceof, as well as the custom function of type guard, are used to persuade the compiler of TypeScript that a value contains a specific type. This way is suggested for narrowing the unknown type values to a certain type.
If you would like to make the compiler trust in the fact that the unknown type value is a type given, a type assertion can be utilized like this:
const value: unknown = "Hello World";
const someString: string = value as string;
const otherString = someString.toUpperCase(); // "HELLO WORLD"
Note that no special checks are performed by TypeScript to ensure the validity of the type assertion. It will lead to an assumption from the type checker that you understand well and believe that the type used in your type assertion is true.
Consequently, an error can arise at runtime if there is a mistake caused by use, especially if an incorrect type is specified.
const value: unknown = 42;
const someString: string = value as string;
const otherString = someString.toUpperCase(); // BOOM
This blog has explained to you why the error “Object is of type unknown” occurs and how to use type guard and type assertion to solve this. We also have given you some notes as well as the pros and cons of this method. You can visit our website more often to acquire more IT knowledge!
Leave a comment