typescript中interface和type的区别

在TypeScript中,interface用于定义对象类型并支持继承和同名合并,适合描述接口;type则更灵活,可定义复杂类型别名,支持交叉和联合类型,但不支持同名合并。interface进行兼容性检查,type则较为宽松。选择使用时,可根据需求的复杂性和场景来决定。
摘要由CSDN通过智能技术生成

在TypeScript中,interface和type都用于定义类型,但它们有以下区别:

  1. 语法
    interface使用关键字interface来定义类型,而type使用关键字type来定义类型。
  2. 定义方式
    • interface 可以通过继承其他interface来扩展自身的属性和方法,也可以多次声明同名的interface,它们会自动合并成一个接口。
    • type可以使用交叉类型(用&连接)或联合类型(用 | 连接)来组合其他类型,但不能直接继承其他type。同样的,多次声明同名的type导致类型冲突错误。
interface Person {
	name: string
}

interface Employee extends Person {
	salary: number;
}

const john: Person = { name: 'John' };

type Dog = {
	name: string;
}

type GuardDog = Dog & {
	isGurading: boolean;
}

const dog: GuardDog = { name: "Buddy", isGuarding: true}
  1. 同名合并
    • 如果你定义了多个同名的interface,它们会被自动合并成一个,合并后的interface会拥有所有定义的属性和方法。
    • type不支持同名合并,如果多次声明同名的type,则会导致类型冲突错误。
interface Person {
	name: string;
}
interface Person{
	age: number;
}

const p: Person = { name: 'John', age: 25 };
  1. 兼容性
    • 对于对象类型,interface会进行兼容性检查以确保属性的兼容性和缺失属性的检查;而type则更加宽松,只要目标类型具有所需的属性即可。
    • 当使用implement关键字实现一个接口时,编译器会强制检查是否实现了所有接口的属性和方法。
interface Animal {
	name: string;
}

type Dog = {
	name: string;
	breed: string;
}

const animal: Animal = { name: 'Tom' };
const dog: Dog = { name: 'Spike', breed: "Labrador"};

animal = dog; // 兼容
dog = animal; // 不兼容

总体来说,interface主要用于定义对象类型和接口的继承,而type则更灵活,可以定义复杂的类型别名。在选择使用interface还是type时,可以根据具体情况和个人偏好来决定。一般情况下,如果需要定义对象的结构或者实现类似接口的功能,可以使用interface;如果需要描述更复杂的类型或进行类型组合,可以使用type。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值