zl程序教程

您现在的位置是:首页 >  前端

当前栏目

Angular 里 unknown 和 any 的区别

Angular 区别 unknown any
2023-09-14 09:04:00 时间

在SAP Spartacus项目里,我们定义的一个配置对象refreshFocus 属性的类型,为unknown:

这个StackOverflow讨论对于unknown和any的区别做了比较清楚的阐述:

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

unknown which is the type-safe counterpart of any.

unknown 和 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.

任何值都能赋给类型为unknown的变量,但是unknown不能赋值给任何除了unknown类型之外的其他类型的变量。

Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type.

在将unknown用类型narrowing转换成更特定的类型之前,无法在unknown类型的变量上执行任何操作。

一些例子:

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)

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

There are often times where we want to describe the least-capable type in TypeScript. This is useful for APIs that want to signal “this can be any value, so you must perform some type of checking before you use it”. This forces users to safely introspect returned values.

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. For example:

any 代表了所有JavaScript的可能值。任何类型的变量都可以赋给any类型的变量,因此可以将any理解成类型系统里所有类型的超类型。

TypeScript编译器允许在类型为any的变量上施加任何操作。

let myVar: any;

myVar[0];
myVar();
myVar.length;
new myVar();

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.

在很多场景下,any的这个特性,很容易被程序员滥用,来规避TypeScript的静态语法检查。因此 unknown 类型应运而生。