×

聊聊 Typescript 中 type 和 interface 基本知识和它们之间的区别

作者:Terry2025.08.19来源:Web前端之家浏览:27评论:0

聊聊 Typescript 中 type 和 interface 基本知识和它们之间的区别

TypeScript 中 type 和 interface 的核心区别在于类型定义范围和扩展机制:interface 专注于对象类型定义并支持声明合并,而 type 可定义任意类型且支持复杂类型运算。‌

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`更灵活,可以用于定义各种复杂类型,并且在一些情况下可以更方便地进行类型组合和操作。

五、使用场景建议

‌优先使用 interface 的情况:

需要声明合并(如扩展第三方库类型)。‌

类需要显式实现接口约束。‌

‌优先使用 type 的情况:

定义联合类型、元组或需要类型运算(如 keyof、条件类型)。‌

为复杂类型创建别名提升代码可读性。‌

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/Typescript-type-interface.html

网友评论文明上网理性发言 已有0人参与

发表评论: