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 useunknownwhen 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.propsIn 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
nevertype 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.Functions with Infinite Loops
If a function contains an infinite loop that never terminates, it can be typed as
never.
Last updated
Was this helpful?