typescript 使用的幾種狀況

接口的建立

能夠使用 type 和 interface 來建立類型函數

type 特有的優勢:

  1. 聲明基本類型別名,聯合類型,元組等類型code

    type S = string;
    
    type IFoo = IBar | string;
  2. 可以使用 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做爲例子get

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  
}

函數類型中參數的獲取

以此爲例子:string

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}
相關文章
相關標籤/搜索