Typescript 中的类型与接口

2025-06-08

Typescript 中的类型与接口

注意:本文中的术语“类型”指的是typeTypescript 中的“ ”别名

根据Typescript 官方文档:“TypeScript 是一种开源语言,它基于 JavaScript(世界上最常用的工具之一)构建,并添加了静态类型定义。” 从长远来看,在我们的项目中实现 TypeScript 可以节省大量时间。但作为开发人员,在使用 TypeScript 中的类型时,我们应该遵循最佳实践和标准。
在本文中,我们将探讨两种类型type别名和之间的区别interface。许多开发人员并不真正了解这两者之间的真正区别。了解了这些区别后,我们可以根据最佳用例来实现它们。

起源

接口用于定义数据结构,例如对象的形状/结构。

类型用于定义数据的类型,例如:原始、联合、交集、元组数据类型。

类型评估时间

类型求值周期有一个微妙的关键区别。type别名的类型求值是立即的,而 的类型求值interface延迟的

类型声明语法

尽管类型和接口可以以类似的方式使用,但它们的声明语法不同。

type BulldogType = {
  name: string;
  height: number;
  weight: number;
}

interface BulldogInterface {
  name: string;
  height: number;
  weight: number;
} 
Enter fullscreen mode Exit fullscreen mode

扩展和实现关键字

在 Typescript 中,我们可以使用 来扩展和实现类型interface。这是使用别名无法实现的type

interface Dog {
  breed: string;
}

interface Bulldog extends Dog {
  isCute: true;
}
Enter fullscreen mode Exit fullscreen mode

路口

我们可以将多个typesinterface用“ &”关键字组合成一个type。但是,我们不能将它们组合成一个interface

type Bulldog = { }
type GermanShepherd = {}

type DogBreeds = Bulldog & GermanShepherd; // valid

interface IBulldog {}
interface IGermanShepherd {}

type IDogBreeds = IBulldog & IGermanShepherd; // valid

Enter fullscreen mode Exit fullscreen mode

工会

联合类型允许我们使用“ ”关键字创建一个新类型,该类型可以具有一个或多个其他类型的值|。我们可以使用 union 关键字
将多个types和组合成一个。但是,我们不能将它们组合成一个interfacetypeinterface

type Bulldog = { }
type GermanShepherd = {}

type DogBreeds = Bulldog | GermanShepherd; // valid

interface IBulldog {}
interface IGermanShepherd {}

type IDogBreeds = IBulldog | IGermanShepherd; // valid
Enter fullscreen mode Exit fullscreen mode

声明合并

interface允许声明合并,而type别名则不允许。Typescript 编译器会智能地将两个或多个同名接口合并为一个声明。

interface IBulldog {
 name: string;
}
interface IBulldog {
 weight: number;
}

const bruno: IBulldog = {
  name: "Bruno",
  weight: 22
}
Enter fullscreen mode Exit fullscreen mode

但是,type一旦使用别名创建类型,别名就无法更改type。因此,无法使用type别名进行声明合并。

type IBulldog = {
 name: string;
}
type IBulldog = {
 weight: number;
}

// Error: Duplicate identifier 'IBulldog'
Enter fullscreen mode Exit fullscreen mode
鏂囩珷鏉ユ簮锛�https://dev.to/ananta/types-vs-interfaces-in-typescript-1g3p
PREV
更新 React 状态时应避免的 3 个错误
NEXT
使用 python 和 flask Docker 架构 Docker 化您的第一个 Web 应用程序 所需文件和配置 如何启动容器 加分点:将 Docker 镜像上传到 Docker Hub