Junior — Middle
Can you explain what the 'unknown' type means in TypeScript and how it differs from 'any'?
sobes.tech AI
Answer from AI
In TypeScript, the unknown type represents a type that can hold any value but requires type checking before use. It is a safer alternative to the any type.
Main differences between unknown and any:
anydisables type checking, allowing you to do anything with the variable without compile-time errors.unknownrequires explicit type checking or type assertion before use, which enhances code safety.
Example:
let valueAny: any = 10;
let valueUnknown: unknown = 10;
// You can call methods on `any` without errors
valueAny.toFixed(2);
// With `unknown`, you need to check the type
if (typeof valueUnknown === 'number') {
valueUnknown.toFixed(2); // now safe
}
Thus, unknown is useful when you need to accept values of unknown type but do not want to lose type safety.