TypeScript typeof 操作符


一、typeof 簡介

在 TypeScript 中, typeof 操作符可以用來獲取一個變量或對象的類型。

interface Person { name: string; age: number; } const sem: Person = { name: "semlinker", age: 30 }; type Sem = typeof sem; // type Sem = Person 

在上面代碼中,我們通過 typeof 操作符獲取 sem 變量的類型並賦值給 Sem 類型變量,之后我們就可以使用 Sem 類型:

const lolo: Sem  = { name: "lolo", age: 5 } 

你也可以對嵌套對象執行相同的操作:

const kakuqo = { name: "kakuqo", age: 30, address: { province: '福建', city: '廈門' } } type Kakuqo = typeof kakuqo; /* type Kakuqo = { name: string; age: number; address: { province: string; city: string; }; } */ 

此外, typeof 操作符除了可以獲取對象的結構類型之外,它也可以用來獲取函數對象的類型,比如:

function toArray(x: number): Array<number> { return [x]; } type Func = typeof toArray; // -> (x: number) => number[]

 

二、const 斷言

TypeScript 3.4 引入了一種新的字面量構造方式,也稱為 const 斷言。當我們使用 const 斷言構造新的字面量表達式時,我們可以向編程語言發出以下信號:

readonly readonly 

下面我們來舉一個 const 斷言的例子:

let x = "hello" as const; type X = typeof x; // type X = "hello" let y = [10, 20] as const; type Y = typeof y; // type Y = readonly [10, 20] let z = { text: "hello" } as const; type Z = typeof z; // let z: { readonly text: "hello"; } 

數組字面量應用 const 斷言后,它將變成 readonly 元組,之后我們還可以通過 typeof 操作符獲取元組中元素值的聯合類型,具體如下:

type Data = typeof y[number]; // type Data = 10 | 20 

這同樣適用於包含引用類型的數組,比如包含普通的對象的數組。這里我們也來舉一個具體的例子:

const locales = [ { locale: "zh-CN", language: "中文" }, { locale: "en", language: "English" } ] as const; // type Locale = "zh-CN" | "en" type Locale = typeof locales[number]["locale"]; 

另外在使用 const 斷言的時候,我們還需要注意以下兩個注意事項:

 

const 斷言只適用於簡單的字面量表達式

 

// A 'const' assertions can only be applied to references to enum members, // or string, number, boolean, array, or object literals. let a = (Math.random() < 0.5 ? 0 : 1) as const; // error let b = Math.random() < 0.5 ? 0 as const : 1 as const; 

 

const 上下文不會立即將表達式轉換為完全不可變

 

let arr = [1, 2, 3, 4]; let foo = { name: "foo", contents: arr, } as const; foo.name = "bar"; // error! foo.contents = []; // error! foo.contents.push(5); // ...works!

vi設計http://www.maiqicn.com 辦公資源網站大全https://www.wode007.com

三、typeof 和 keyof 操作符

在 TypeScript 中, typeof 操作符可以用來獲取一個變量或對象的類型。而 keyof 操作符可以用於獲取某種類型的所有鍵,其返回類型是聯合類型。了解完 typeof 和 keyof 操作符的作用,我們來舉個例子,介紹一下它們如何結合在一起使用:

const COLORS = { red: 'red', blue: 'blue' } // 首先通過typeof操作符獲取Colors變量的類型,然后通過keyof操作符獲取該類型的所有鍵, // 即字符串字面量聯合類型 'red' | 'blue' type Colors = keyof typeof COLORS let color: Colors; color = 'red' // Ok color = 'blue' // Ok // Type '"yellow"' is not assignable to type '"red" | "blue"'. color = 'yellow' // Error


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM