TypeScript 3.0 introduces a new type called
unknown
that does exactly that. Much likeany
, any value is assignable tounknown
; however, unlikeany
, you cannot access any properties on values with the typeunknown
, nor can you call/construct them. Furthermore, values of typeunknown
can only be assigned tounknown
orany
.As an example, swapping the above example to use
unknown
instead ofany
forces turns all usages of foo into an error:
let foo: unknown = 10;
// Since `foo` has type `unknown`, TypeScript
// errors on each of these usages.
foo.x.prop;
foo.y.prop;
foo.z.prop;
foo();
new foo();
upperCase(foo);
foo `hello world!`;
function upperCase(x: string) {
return x.toUpperCase();
}
I recently started to code in TypeScript, and here is my questions:
1. It seems to me, unknown
can be the complete alternative to any
.
Of course, a code written in native JavaScript requires to use any
type automatically in TypeScript, but when we start from scratch to code in pure TypeScript, is there any reason to employ any
type instead of unknown
from version 3.0?
2. What is the diffrence between unknown
and generics
?
For instance,
const A = <T>(value: T): T => value;
const A1 = (value: unknown) => value;
console.log(A<string>('Hello'), A<number>(100));
const B = <T, U>(t: T, u: U) => {
console.log(t);
console.log(u);
};
const B1 = (t: unknown, u: unknown) => {
console.log(t);
console.log(u);
};
B<string, number>('Hello', 100);
B<number, string>(100, 'Hello');
and suppose the arugument value: unknown
is originally defintely typed, the type of the value is identified, so it seems to me there is no reason to pass T
explicitly.
Thanks.