ts 中 type 和 interface 的区别
在 TypeScript 中,`type` 和 `interface` 都用于定义类型,但它们之间有一些区别:
一、定义方式
1. interface
使用`interface`关键字来定义接口。
通常用于描述对象的形状,即对象的属性和方法。
interface Person {name: string;age: number;}
2. type
使用`type`关键字来定义类型别名或联合类型、交叉类型等复杂类型。
type Age = number;type Status = "active" | "inactive";
二、可扩展性
1. interface
可以通过继承来扩展。
interface Student extends Person {grade: number;}
2. type
对于类型别名,不能直接扩展,但可以通过交叉类型来模拟扩展。
type PersonWithAddress = Person & { address: string };
三、重复定义
1. interface
可以多次定义同一个接口,它们会自动合并。
interface Person {name: string;}interface Person {age: number;}// 等效于interface Person {name: string;age: number;}
2. type
不能重复定义同一个类型别名。
四、实现方式
1. interface
主要用于描述对象的结构,通常在面向对象编程中使用。
类可以实现接口。
class Employee implements Person {name: string;age: number;}
2. type
更灵活,可以用于定义各种类型,不限于对象结构。
总结:`interface` 更适合用于描述对象的形状和结构,以及在面向对象编程中使用。而`type`更灵活,可以用于定义各种复杂类型,并且在一些情况下可以更方便地进行类型组合和操作。