【學習筆記】TypeScript typeof 操作符


【學習筆記】TypeScript typeof 操作符

原文:http://www.semlinker.com/ts-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[]

 


免責聲明!

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



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