Angular 里 unknown 和 any 的区别
在SAP Spartacus項目里,我們定義的一個配置對象refreshFocus 屬性的類型,為unknown:
這個StackOverflow討論對于unknown和any的區(qū)別做了比較清楚的闡述:
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類型的變量上執(zhí)行任何操作。
一些例子:
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 variableThere 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理解成類型系統(tǒng)里所有類型的超類型。
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的這個特性,很容易被程序員濫用,來規(guī)避TypeScript的靜態(tài)語法檢查。因此 unknown 類型應運而生。
總結
以上是生活随笔為你收集整理的Angular 里 unknown 和 any 的区别的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信爱心贝有什么用
- 下一篇: SAP Spartacus B2B Un