Middle
Знакома ли с типом unknown? Чем он отличается от any?
sobes.tech AI
Answer from AI
The unknown type in TypeScript is a type that represents a value of an unknown type. It is more strict than any because with a variable of type unknown, you cannot perform operations or assign it to other types without checking.
Unlike any, which disables type checking and allows you to do anything with the variable, unknown requires explicit type narrowing before use, which enhances code safety.
Example:
let value: unknown = "hello";
// Error: Object is of type 'unknown'.
// console.log(value.length);
if (typeof value === "string") {
console.log(value.length); // now safe
}
let anything: any = "hello";
console.log(anything.length); // works without errors
Thus, unknown is useful when you need to accept values of an unknown type but still want to maintain strict typing and safety.