Any vs Unknown vs Never
Any
It can hold any value
Skip the type checking , which may cause runtime error
Unknown
Any value can be assigned to a variable of type
unknown
. So useunknown
when a value might have any typeHowever, when you try to access something from it, typescript will give you an error.
let test:unknown;
test.length;
test.join(",");
test.toFixed(2);
test.props
In order to solve the issue, it is needed to add type checking to narrow down the type
let test: unknown;
if (test instanceof String) test.length;
if (Array.isArray(test)) test.join(',');
if (test instanceof Number) test.toFixed(2);
if (test instanceof Object) (test as { props: string }).props;
Never
never
type represents a value that never occursFunctions That Throw Errors
If a function always throws an error and never returns a value, its return type can be annotated as
never
.function throwError(message: string): never { throw new Error(message); }
Functions with Infinite Loops
If a function contains an infinite loop that never terminates, it can be typed as
never
.function infiniteLoop(): never { while (true) { // Do something without ever returning } }
Last updated
Was this helpful?