let a: unknown = 5; let b: any = 5; // Trying to add 10 to both variables // console.log(a + 10); // Uncommenting this line causes error console.log(b + 10);
The variable a is of type unknown, so TypeScript does not allow operations like addition without type checking. This causes a compilation error if you try a + 10. The variable b is of type any, so the addition is allowed and outputs 15.
unknown over any in TypeScript?unknown is safer because it forces the programmer to check the type before using the value, preventing many runtime errors. any disables type checking and can lead to bugs.
function process(value: unknown) { console.log(value.toFixed(2)); } process(3.1415);
The value parameter is unknown, so you cannot directly call methods on it without first checking or asserting its type. This causes a compilation error.
let val: unknown = "123"; let num = val as number; console.log(num + 1);
The assertion val as number does not perform any runtime conversion; it only tells TypeScript to treat val as a number. At runtime, num remains the string "123", so num + 1 results in string concatenation: '1231'.
unknown and any in TypeScript?unknown forces the programmer to check or assert the type before using the value, preventing many errors. any disables type checking, allowing any operation, which can lead to runtime errors.