# interface 和 type 有什么异同点?

interface-declarations (opens new window)

An interface cannot declare a property with the same name as an inherited private or protected property.

type-aliases (opens new window)

An interface can have multiple merged declarations, but a type alias for an object type literal cannot

# 相同点

  • 描述一个对象或者函数
export interface IUser {
  id: string | number;
  name: string;
  age?: number;
}

export interface IGetUser {
  (id: string | number): IUser;
}

export type User = {
  name: string;
  age?: number;
}

export type GetUser = (id: string | number): User;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  • 允许类型拓展(type不能使用extends关键字)
interface FE extends IUser {
  type: string;
}

type FE = { type: string; } & User;

1
2
3
4
5
6

# 不同点

  • type 可以声明基本类型别名, 联合类型, 元组等类型

  • interface 能够声明合并

interface IUser {
  id: string | number;
}

interface IUser {
  name: string;
  age?: number;
}

// =>
interface IUser {
  id: string | number;
  name: string;
  age?: number;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 参考资料

handbook - type-inference (opens new window)

interfaces (opens new window)

typescript-interfaces-vs-types (opens new window)

handbook - differences-between-type-aliases-and-interfaces (opens new window)