any vs unknown vs never
any
simply turns off the type checker, and we can assign anything to variable typed any
.
The problem is that we can call a method on undefined
and typescript will not complain.
unknown
basically a stricter version of any
, where we can also assign anything to variable typed unknown
, but we cannot call any method on it.
unknown
enforces us to add a check before using anything from the variable.
let foo: unknown = 23;
if (foo <= 23) {
} // squiggly line: 'foo' is of type 'unknown'
if (typeof foo === "number" && foo <= 23) {
} // ok
never
The opposite to type any
, used when we have do not have anything to assign to a value.
Some cases:
if-else block
function processValue(value: string) {
if (typeof value === "string") {
// do something
} else {
assertNever(value); // this line ensures that all possible types are handled
}
}
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${value}`);
}
switch block
function processValue(value: string) {
switch (typeof value) {
case "string":
// do something
break;
default:
assertNever(value); // ensures all cases are covered
}
}
function which throws error
function throwError(message: string): never {
throw new Error(message);
}