新聞中心
本文是關(guān)于 TypeScript 中的 type assertions 的,它與其他語(yǔ)言中的類(lèi)型強(qiáng)制轉(zhuǎn)換有相似之處,并通過(guò) as 運(yùn)算符執(zhí)行。

成都創(chuàng)新互聯(lián)公司專(zhuān)注于涵江企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站,商城網(wǎng)站建設(shè)。涵江網(wǎng)站建設(shè)公司,為涵江等地區(qū)提供建站服務(wù)。全流程按需策劃,專(zhuān)業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,成都創(chuàng)新互聯(lián)公司專(zhuān)業(yè)和態(tài)度為您提供的服務(wù)
類(lèi)型斷言
類(lèi)型斷言使我們可以覆蓋 TypeScript 為存儲(chǔ)位置計(jì)算的靜態(tài)類(lèi)型,這對(duì)于解決類(lèi)型系統(tǒng)的限制很有用。
類(lèi)型斷言與其他語(yǔ)言中的類(lèi)型強(qiáng)制轉(zhuǎn)換有相似之處,但是它們不會(huì)引發(fā)異常,并且在運(yùn)行時(shí)也不做任何事情(它們確實(shí)會(huì)靜態(tài)執(zhí)行一些少量的檢查)。
- const data: object = ['a', 'b', 'c']; // (A)
- // @ts-ignore: Property 'length' does not exist on type 'object'.
- data.length; // (B)
- assert.equal(
- (data as Array
).length, 3); // (C)
- 在 A 行中,我們把 Array 的類(lèi)型擴(kuò)展為 object。
- 在 B 行中,我們看到此類(lèi)型不允許訪問(wèn)任何屬性。
- 在 C 行中,我們用類(lèi)型斷言(運(yùn)算符 as)告訴 TypeScript data 是一個(gè)Array。現(xiàn)在就可以訪問(wèn)屬性 .length 了。
類(lèi)型斷言是不得已的方法,應(yīng)盡可能的避免。他們(暫時(shí))刪除了靜態(tài)類(lèi)型系統(tǒng)為我們提供的安全網(wǎng)。
注意,在 A 行中,我們還覆蓋了 TypeScript 的靜態(tài)類(lèi)型,不過(guò)是通過(guò)類(lèi)型注釋完成的。這種覆蓋方式比類(lèi)型聲明要安全得多,因?yàn)槟憧梢宰龅氖虑樯俚枚唷ypeScript 的類(lèi)型必須能夠分配給注釋的類(lèi)型。
(1) 類(lèi)型斷言的替代語(yǔ)法
TypeScript 對(duì)于類(lèi)型斷言有另一種“尖括號(hào)”語(yǔ)法:
>data
該語(yǔ)法已經(jīng)過(guò)時(shí),并且與 React JSX 代碼(在 .tsx 文件中)不兼容。
(2) 示例:聲明一個(gè)接口
為了訪問(wèn)任意對(duì)象 obj 的屬性 .name,我們暫時(shí)將 obj 的靜態(tài)類(lèi)型更改為 Named(A行和B行)。
- interface Named {
- name: string;
- }
- function getName(obj: object): string {
- if (typeof (obj as Named).name === 'string') { // (A)
- return (obj as Named).name; // (B)
- }
- return '(Unnamed)';
- }
(3) 示例:聲明索引簽名
在以下代碼中,我們?cè)谛?A 用了類(lèi)型斷言 as Dict ,以便可以訪問(wèn)其推斷類(lèi)型為 object 的值的屬性。也就是說(shuō),用靜態(tài)類(lèi)型 Dict 覆蓋了推斷的靜態(tài)類(lèi)型 object。
- type Dict = {[k:string]: any};
- function getPropertyValue(dict: unknown, key: string): any {
- if (typeof dict === 'object' && dict !== null && key in dict) {
- // %inferred-type: object
- dict;
- // @ ts-ignore:元素隱式具有“any”類(lèi)型,因?yàn)?/li>
- // 類(lèi)型'string'的表達(dá)式不能用于索引類(lèi)型'{}'。
- // 在類(lèi)型“ {}”上沒(méi)有找到參數(shù)類(lèi)型為'string'的索引簽名。
- dict[key];
- return (dict as Dict)[key]; // (A)
- } else {
- throw new Error();
- }
- }
與類(lèi)型斷言相關(guān)的構(gòu)造
(1) 非空斷言運(yùn)算符(后綴 !)
如果值的類(lèi)型是包含 undefined 或 null 類(lèi)型的聯(lián)合,則 non-nullish聲明運(yùn)算符(或 non-null 聲明運(yùn)算符)將從聯(lián)合中刪除這些類(lèi)型。我們告訴 TypeScript:“這個(gè)值不能是 undefined 或 null?!币虼?,我們可以執(zhí)行這兩個(gè)值的類(lèi)型所阻止的操作,例如:
- const theName = 'Jane' as (null | string);
- // @ts-ignore: Object is possibly 'null'.
- theName.length;
- assert.equal(
- theName!.length, 4); // OK
(2) 示例 – Maps: .has() 之后的 .get()
使用 Map 方法 .has() 之后,我們知道 Map 具有給定的鍵。遺憾的是,.get() 的結(jié)果不能反映這一點(diǎn),這就是為什么我們必須使用 nullish 斷言運(yùn)算符的原因:
- function getLength(strMap: Map
, key: string): number { - if (strMap.has(key)) {
- // We are sure x is not undefined:
- const value = strMap.get(key)!; // (A)
- return value.length;
- }
- return -1;
- }
由于 strMap 的值永遠(yuǎn)不會(huì)是 undefined,因此我們可以通過(guò)檢查 .get() 的結(jié)果是否為 undefined 來(lái)檢測(cè)丟失的 Map 條目(A 行):
- function getLength(strMap: Map
, key: string): number { - // %inferred-type: string | undefined
- const value = strMap.get(key);
- if (value === undefined) { // (A)
- return -1;
- }
- // %inferred-type: string
- value;
- return value.length;
- }
(3) 定值斷言
如果打開(kāi) strict 屬性初始化,有時(shí)需要告訴 TypeScript 我們確實(shí)初始化某些屬性——即使它認(rèn)為我們不需要這樣做。
這是一個(gè)例子,盡管 TypeScript 不應(yīng)這樣做,但它仍會(huì)報(bào)錯(cuò):
- class Point1 {
- // @ts-ignore: Property 'x' has no initializer and is not definitely
- // assigned in the constructor.
- x: number;
- // @ts-ignore: Property 'y' has no initializer and is not definitely
- // assigned in the constructor.
- y: number;
- constructor() {
- this.initProperties();
- }
- initProperties() {
- this.x = 0;
- this.y = 0;
- }
- }
如果我們?cè)?A 行和 B 行中使用“定值分配斷言”(感嘆號(hào)),則錯(cuò)誤會(huì)消失:
- class Point2 {
- x!: number; // (A)
- y!: number; // (B)
- constructor() {
- this.initProperties();
- }
- initProperties() {
- this.x = 0;
- this.y = 0;
- }
- }
當(dāng)前名稱(chēng):TypeScript中的類(lèi)型斷言
當(dāng)前網(wǎng)址:http://www.dlmjj.cn/article/cddepdi.html


咨詢(xún)
建站咨詢(xún)
