TypeScript中interface和type的不同之处,看这些就够了

416 阅读2分钟

官方文档说明

先看下官方文档对两者的说明

  • An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot.
  • An interface can have multiple merged declarations, but a type alias for an object type literal cannot.

下面是对这部分说明的理解的例子

相同点

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

interface

interface Animal {
    color: string;
    name: string;
}

interface Dog {
    (name: string, color: string): void;
}

type

type Animal = {
    color: string;
    name: string;
}

type Dog = (name: string, color: string): void;

都允许扩展(extends)

interface 和 type 都可以拓展,并且两者并不是相互独立的,也就是说 interface 可以 extends type, type 也可以 extends interface 。 虽然效果差不多,但是两者语法不同。

interface extends interface

interface Animal { 
    name: string;
}
interface Dog extends Animal { 
    color: string;
}

type extends type

type Animal = {
    name: string;
}
type Dog = Animal & {
    color: string;
}

interface extends type

type Animal = {
    name: string;
}
interface Dog extends Animal {
    color: string;
}

type extends interface

interface Animal {
    name: string;
}
type Dog = Animal & {
    color: string;
}

不同点

type 可以而 interface 不可以

  • type 可以声明基本类型别名,联合类型,元组等类型
// 基本类型
type Name = string;

// 联合类型
interface Pig {
    eat();
}
interface Dog {
    run();
}

type Animal = Pig | Dog;

// 具体定义数组每个位置类型
type List = [Pig, Dog];
  • type 语句中还可以使用 typeof 获取实例的 类型进行赋值
// 当你想获取一个变量的类型时,使用 typeof
let div = document.createElement('div');
type Element = typeof div
  • 其他骚操作
type StringOrNumber = string | number;  
type Text = string | { text: string };  
type NameLookup = Dictionary<string, Person>;  
type Callback<T> = (data: T) => void;  
type Pair<T> = [T, T];  
type Coordinates = Pair<number>;  
type Tree<T> = T | { left: Tree<T>, right: Tree<T> };

interface 可以而 type 不可以

interface 能够声明合并

interface Dog {
  name: string;
  color: string;
}
 
interface Dog {
  eat();
}
 
/*
Dog 接口为 {
  name: string;
  color: string;
  eat();
}
*/

总结

一般来说,如果不清楚什么时候用interface/type,能用 interface 实现,就用 interface , 如果不能再用type 。

参考链接