Sub topic 11
any versus unknown
This chapter assumes you know the primitive types, union types, and type narrowing with typeof. You should also be comfortable with JSON.parse returning data of unknown shape, and with running tsc in strict mode.
TypeScript offers two types for values whose shape you cannot know at compile time: any and unknown. Both accept any value on assignment. They differ in what the compiler lets you do with the value afterward.
Why `any` is risky
any turns off type checking for the value it describes. The compiler accepts every operation on it, so errors surface only at runtime.
let fromAny: any = "hello";
let n: number = fromAny; // no compile error
console.log(n.toFixed(2)); // runtime TypeError: n.toFixed is not a functionThe assignment to number passes because any is assignable to every type. The bug appears only when the program runs. Each any spreads silently to the values derived from it, so one any can remove checking from a whole chain of code.
How `unknown` forces safety
unknown accepts any value too, but the compiler blocks every operation until you narrow the type with a check.
const raw: unknown = JSON.parse('{"age": 30}');
// raw.age; // Error: 'raw' is of type 'unknown'.
if (typeof raw === "object" && raw !== null && "age" in raw && typeof raw.age === "number") {
console.log(raw.age.toFixed(1)); // prints 30.0
}Each check narrows the type. After the typeof and in checks, TypeScript knows raw.age is a number, so the call to toFixed type-checks.
Common errors
- Using
anyas a shortcut for a hard type. Declaring a parameteranyto silence an error hides the mistake. Preferunknown, then narrow. - Asserting
unknowninto a type without checking.raw as { age: number }compiles, but it trusts the data. If the JSON lacksage, the program fails later. - Assuming
anyis inferred. The compiler infersanyonly in a few cases, such as a parameter with no annotation undernoImplicitAny: false. Withstricton, an unannotated parameter is an error, notany.
Exercises
Exercise
Why does the compiler accept const n: number = anyValue but reject const n: number = unknownValue?
Show answer
any is assignable to every type and disables checks, so the compiler accepts it. unknown can be assigned only to unknown or any without a narrowing check, so assigning it to number requires a check first.
Exercise
Rewrite function len(x: any) { return x.length; } so it accepts unknown and returns 0 when x has no string or array length.
Show answer
function len(x: unknown): number { if ((typeof x === "string") || Array.isArray(x)) { return x.length; } return 0; }