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:
anyallows any operation, which may lead to runtime errors.unknownforces type checks, improving type safety.
Read more about TypeScript unknown