type和interface的區別


1. type可以聲明 基本類型,聯合類型,元組 的別名,interface不行

// 基本類型別名
type Name = string

// 聯合類型
interface Dog {
    wong();
}
interface Cat {
    miao();
}

type Pet = Dog | Cat

// 具體定義數組每個位置的類型
type PetList = [Dog, Pet]

2. type 語句中可以使用 typeof 獲取類型實例

// 當你想獲取一個變量的類型時,使用 typeof
let div = document.createElement('div');
type B = typeof div

3. type 支持類型映射,interface不支持

type Keys = "firstname" | "surname"

type DudeType = {
  [key in Keys]: string
}

const test: DudeType = {
  firstname: "Pawel",
  surname: "Grzybek"
}

// 報錯
//interface DudeType {
//  [key in keys]: string
//}

4. interface能夠聲明合並,type不能


免責聲明!

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



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