日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Angular 里 unknown 和 any 的区别

發布時間:2023/12/19 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 里 unknown 和 any 的区别的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。