typescript 使用的幾種情況


接口的創建

可以使用 type 和 interface 來創建類型

type 特有的優點:

  1. 聲明基本類型別名,聯合類型,元組等類型
    type S = string;
    
    type IFoo = IBar | string;
  1. 可使用 typeof 獲取實例的類型賦值
    const a:number = 1;
    const IA = typeof a;
    // IA 被 ts 識別為 number

interface 特有的優點

interface 能夠聲明合並

interface IFoo {  
  name:string  
}  
interface IFoo {  
  age:number  
}
// 等於
type IFoo = {
    name:string 
    age:number
}

關於對象

獲取對象

以IFoo作為例子

interface IFoo {  
  name:string  
  age:number  
  gender:string  
}  

獲取接口的單個屬性的類型

type IBar = IFoo["name"]
// IBar = string

獲取接口中一或多個屬性,並將其合並為一個接口

type IBar = Pick<IFoo, "name">
// IBar = {name: string}
type IBar = Pick<IFoo, "name" | "age">
// IBar = {name: string, age: number}

忽略接口中的某些屬性,將剩余屬性作為一個接口

type IBar = Omit<IFoo, "name">
// IBar = {age: number, gender: string}

獲取接口中所有鍵

type IBar = keyof IFoo
// IBar = "name" | "age" | "gender"

獲取接口中所有鍵對應的值

type IBar = IFoo[keyof IFoo]
// IBar = string | number

創建對象

創建多個重復值的對象

type IBar = Record<"name" | "age", string>
// IBar = {name: string, age: string}

使用例子

interface IFoo {  
  name: string  
  age: string  
  gender: string  
  
  getSkill(): void  
  
  setSkill: (skill: string[]) => void  
}
// 生成一個新類型,將 age 和 gender 的類型修改為 number,其他的類型不變
// 使用上述知識 聲明一個新的高級類型IBar:
type IBar<K extends string,T = number> = (Record<K, T> & Omit<IFoo, K>)

type IBaz = IBar<"age" | "gender">
// 生成新的類型 IBaz ,符合上述描述
// 並且使用 Ibar 可將 age 和 gender (或其他)更改為任意其他類型 如:
type IBax = IBar<"age" | "gender" | "name", string[]>

關於函數

函數類型創建

創建函數類型的兩種方式

interface IFoo {  
  name: string  
  age: number  
  gender: string  
  
  getSkill(): void  // type 不支持此種聲明
  
  setSkill: (skill: string[]) => void  
}

函數類型中參數的獲取

以此為例子:

type IFoo = (name: string, age: number) => { name: string, age: number, gender: string }

獲取函數的參數類型:

type IBar = Parameters<IFoo>  
  
// IBar = [string, number]

獲取函數的返回類型:

type IBar = ReturnType<IFoo>  
  
// IBar = {name: string, age: number, gender: string}


免責聲明!

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



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