TypeScript中interface和type的差别是什么?
在TypeScript中,interface和type都是定义类型的关键字,但它们在使用和行为上存在一些差异。理解这些差异对于在合适的场景中选择正确的抽象方式至关重要。
1. interface
interface在TypeScript中主要用于定义对象的结构,它是一种方式来告诉编译器一个对象应该具有哪些形状。
interface Person {
name: string;
age: number;
}
const user: Person = {
name: "Alice",
age: 30
};
在这个例子中,我们定义了一个Person接口,它要求实现的对象必须有两个属性:name(字符串类型)和age(数字类型)。
2. type
type关键字用于定义更广泛的类型,不仅仅是对象结构。它可以用来给基本类型、联合类型、元组、函数等赋予一个新名字。
type PersonType = {
name: string;
age: number;
};
const user: PersonType = {
name: "Alice",
age: 30
};
在这个例子中,我们使用type定义了一个PersonType类型别名,它与Person接口等效。
3. interface和type的差别
3.1. 扩展性
- interface:可以被扩展(extends),允许多个接口合并到一个接口中。
- type:没有扩展的概念,但可以使用交叉类型(&)来组合多个类型。
3.2. 声明合并
- interface:当有两个相同的接口声明时,它们会合并。
- type:相同的类型别名声明会导致编译错误。
3.3. 重新声明
- interface:可以在不同的地方重复声明同一个接口,每次声明都会为接口添加额外的成员,这被称为声明合并。
- type:重复的类型别名声明是不允许的。
3.4. 类实现
- interface:类可以使用implements关键字来实现接口。
- type:不能用于类的实现。
// 使用interface
interface Person {
name: string;
}
interface Person {
age: number; // 这会与上面的Person接口合并
}
class User implements Person {
name: string;
age: number;
}
// 使用type
type PersonType = {
name: string;
};
// 下面的声明会导致错误,因为PersonType已经被声明过了
type PersonType = {
age: number;
};
在这个例子中,我们展示了如何使用interface和type来定义类型,并展示了声明合并和重新声明的差异。
3.5. 基本类型别名
- interface:不能用于基本类型的别名声明。
- type:可以用于基本类型、联合类型、元组、函数等的别名声明。
// 使用type定义基本类型的别名
type ID = string;
const id: ID = "123"; // 使用别名ID
// 使用type定义复杂的类型别名
type User = [string, number]; // 元组类型
type Callback = () => void; // 函数类型
在这个例子中,我们使用type来定义基本类型、元组和函数的别名