관리 메뉴

Dev Blog

Difference "any VS unknown " 본문

Development Notes/Javascript & Typescript

Difference "any VS unknown "

Yongjae Kim 2021. 7. 5. 12:45
[..] unknown which is the type-safe counterpart of any. Anything is assignable to unknown, but unknown isn't assignable to anything but itself and any without a type assertion or a control flow based narrowing. Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type.
let myVar: unknown;

let myVar1: unknown = myVar;   // No error
let myVar2: any = myVar;       // No error
let myVar3: boolean = myVar;   // Type 'unknown' is not assignable to type 'boolean'

let vAny: any = 10;          // We can assign anything to any
let vUnknown: unknown =  10; // We can assign anything to unknown just like any 

let s1: string = vAny;     // Any is assignable to anything 
let s2: string = vUnknown; // Invalid; we can't assign vUnknown to any other type (without an explicit assertion)

// The following operations on myVar all give the error:
// Object is of type 'unknown'
myVar[0];
myVar();
myVar.length;
new myVar();

vAny.method();     // Ok; anything goes with any
vUnknown.method(); // Not ok; we don't know anything about this variable

For more detail, 

any type

The any type represents all possible JS values. Every type is assignable to type any. Therefore the type any is an universal supertype of the type system. The TS compiler will allow any operation on values typed any. 

In many occasions this is too lenient of the TS compiler. i.e. it will allow operations which we could have known to be resulting into a runtime error.

unknown type  

The unknown type represents (just like any) all possible JS values. Every type is assignable to type unknown. Therefore the type unknown is another universal supertype of the type system (alongside any).

However, the TS compiler won't allow any operation on values typed unknown. Compare to the runtime error

which can be arised on using any type, unknown type prevent this runtime error when compiling. 

Furthermore, the unknown type is only assignable to the type any.

 

 

Source from 

https://stackoverflow.com/questions/51439843/unknown-vs-any

Comments