What is the purpose of the unknown type? How is it different from any?
Answer
The unknown
type is a safer alternative to any
. It represents any value but requires type-checking before performing operations on it.
let value: unknown;
value = "Hello";
if (typeof value === "string") {
console.log(value.toUpperCase()); // Safe operation
}
// let num: number = value; // Error without type-checking
Difference from any
:
any
allows any operation, which may lead to runtime errors.unknown
forces type checks, improving type safety.
Read more about TypeScript unknown