Skip to content
On this page

interface和type

定义数组得方法:

Array<number>number[] 含义一样都是代表数组

ts
const a:Array<number> = [1,2,3];
const a:number[] = [1,2,3];

定义对象得方法:

ts
interface DemoProps {
  a: string;
  b: number;
}

const obj: DemoProps = {
 a: '123',
 b: 123,
}

type DemoProps1 = {
  a: string;
  b: number;
}

定义一个函数:

ts
// 示例1:

type DemoProps1 = () => string;

// 示例2:
interface DemoProps {
  fn(a: string): string; // 有一个参数a string, 返回值是string
  fn1: (a: number) => string; // 有一个参数a number, 返回值是string
}

对象未知key、value(不想定义其他作用不大属性得时候)

ts
interface DemoProps {
  a: string;
  b: number;
  [propName: string]: any; // 这里可以作为不想关注得一些字段
}

interface和type的区别

interface和type的区别

相同点

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

  • 都允许拓展(extends)

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

不同点

  • type 可以声明基本类型别名,联合类型,元组等类型,而 interface 不行
  • type 语句中还可以使用 typeof 获取实例的 类型进行赋值,而 interface 不行
  • type还可以定义联合类型等
  • interface 能够声明合并,而 type 不行

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

Released under the MIT License.