Angular 里 unknown 和 any 的区别
在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 类型应运而生。
相关文章
- Angular路由与Nodejs路由的区别
- [Angular] Working with FormArray
- [Angular 2] Set Values on Generated Angular 2 Templates with Template Context
- [Angular2 Form] Angular 2 Template Driven Form Custom Validator
- [Immutable + AngularJS] Use Immutable .List() for Angular array
- [Angular2 Animation] Control Undefined Angular 2 States with void State
- [Angular 2] Building a Toggle Button Component
- [Angular 2] 8. Better ES5 Code
- 运行在 SSR 模式下的 Angular 应用的内存泄漏问题分析
- Angular 依赖注入 UseClass 和 UseExisting 的区别 - 一个实际的测试例子
- 使用 Angular Transfer State 的一个具体例子
- Angular jasmine单元测试框架spec的运行时数据结构
- Angular rxjs源代码分析:range(0, 10)的实现
- atitit.React 优缺点 相比angular react是最靠谱的web ui组件化方案了
- Atitit. js mvc 总结(2)----angular 跟 Knockout o99 最佳实践
- 什么是 Angular library 的 secondary entry points?
- Angular应用Base Element Href属性的设置
- 【华为云技术分享】三大前端技术(React,Vue,Angular)探密(上)