typescript type 和 interface 的区别

  • Post author:
  • Post category:其他




1. interface侧重于描述数据结构,type侧重于描述类型

interface A{ name:string; } 
type B = 'bb'|'cc' 



2. 都可以描述一个对象或者函数

interface user {
  name: string;
  age: number
}
interface setUser {
  (name: string, age: number): void
}

type hoster = {
  name: string;
  age: number;
}
type setHoster = (name: string, age: number) => void



3. interface 可以定义相同的类型名称,多个相同类型名称会合并,type 不可以

interface Window {
  title: string
}

interface Window {
  ts: TypeScriptAPI
}

const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});
type Window = {
  title: string
}

type Window = {
  ts: TypeScriptAPI
}

 // Error: Duplicate identifier 'Window'.



4. interface 可以继承, type不可以


interface Animal {
  name: string
}

interface Bear extends Animal {
  honey: boolean
}

const bear = getBear() 
bear.name
bear.honey
type Animal = {
  name: string
}

type Bear = Animal & { 
  honey: boolean 
}

const bear = getBear();
bear.name;
bear.honey;



5. type专属功能

// type专属 联合类型

interface Dog {
  wang()
}
interface Cat {
  miao()
}
type Pet = Dog | Cat
type PetList = [Dog,Cat]



版权声明:本文为alokka原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。