Skip to main content

interface 与 type

在 TypeScript 中可以用 interface 和 type 来定义接口类型。

interface 与 type 的区别

  1. interface 同名可以多次定义,在用的时候会自动合并,但是 type 同名不能多次定义。
interface User {
name: string;
}

interface User {
age: number;
}

const user: User = {
name: 'remy',
age: 2,
};

所以可以使用 Interface 来扩展一个类型的定义。另外,如果 interface 与 class 同名,那么通过该 class 生成的对象也会有 interface 定义的接口,他们会聚合。

  1. interface 可以继承,type 不可以继承,一般 type 是通过&符号来实现继承。

定义构造函数

定义一个函数类型

使用 type

type FunctionType = () => string;

const func: FunctionType = () => {
return 'func';
};
func();

使用 interface

interface FunctionInterface {
(name: string): string;
}
const funcInterfaceInstance: FunctionInterface = (name: string) => {
return `hello, ${name}`;
};
funcInterfaceInstance('remy');

定义一个数组

使用 type

type NumberListType = {
[index: number]: string;
};

const numbers: NumberListType = ['one', 'two'];
console.log(numbers);

使用 interface

interface NumberListInterface {
[index: number]: string;
}
const numbers: NumberListInterface = ['one', 'two'];
console.log(numbers);