当前位置: 首页 > news >正文

TypeScript 中 interface 与 type的使用注意事项 及区别详细介绍

interfact 与 type 的区别及使用方法

一、 interfact 与 type主要区别

请添加图片描述

二、 interfact 与 type具体用法

1. 定义对象类型

interface 的典型用法:

interface Person {
  name: string;
  age: number;
  greet(): void;
}

type 的等效定义:

type Person = {
  name: string;
  age: number;
  greet(): void;
};
2. 扩展(继承)

interface 使用 extends

interface Employee extends Person {
  salary: number;
}

type 使用交叉类型 &

type Employee = Person & {
  salary: number;
};
3. 联合类型(仅 type 支持)
type Result = Success | Error; // 联合类型
interface Success { data: string }
interface Error { message: string }
4. 元组类型(仅 type 支持)
type Coordinates = [number, number];
5. 声明合并(仅 interface 支持)
interface User { name: string }
interface User { age: number }

// 最终合并为:
// interface User { name: string; age: number }
6. 复杂类型别名(仅 type 支持)
type StringOrNumber = string | number; // 联合类型
type Callback = (data: string) => void; // 函数类型
type Nullable<T> = T | null; // 泛型别名

三、 interfact 与 type使用场景

1、优先 interface:的场景

定义对象结构(如 API 响应、组件 Props)

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

通过 implements 约束类的实现

2、优先 type:的场景

定义联合类型、交叉类型、元组等复杂类型。

需要类型别名简化重复代码(如 type ID = string)

需要直接操作字面量类型(如 type Status = "success" | "error")

四、总结

interface 更适合面向对象的类型设计,强调可扩展性和实现
type 更灵活,适合定义任意复杂类型,尤其是联合类型工具类型
两者在大部分场景下可以互换,但需根据语义和需求选择。
实际开发中,团队可根据规范统一选择,例如默认使用 interface 定义对象,用 type 处理复杂类型。

http://www.dtcms.com/a/66870.html

相关文章:

  • TypeScript深度解析:从类型系统到工程化实践
  • MCP服务协议详细介绍
  • 【Windows】Wan 2.1 视频生成模型本地部署
  • xxl-job部署在docker-destop,实现定时发送预警信息给指定邮箱
  • 年龄与疾病(信息学奥赛一本通-1106)
  • Qt C++ 常用压缩库推荐 快速压缩 解压缩数据
  • Java是怎么解决并发问题的?
  • 高效图像处理工具:从需求分析到落地实现
  • 【vue + JS】OCR图片识别、文字识别
  • react对比vue的核心属性
  • 2340单点修改、区间查询
  • 独立开发记录:使用Trae和Cloudflare快速搭建了自己的个人博客
  • 深度学习与大模型-矩阵
  • 解数独 (leetcode 37
  • 生化混合智能技术(Biochemical Hybrid Intelligence, BHI)解析与应用
  • devServer changeOrigin不管用
  • 101.在 Vue 3 + OpenLayers 使用 declutter 避免文字标签重叠
  • RTSP协议规范与SmartMediaKit播放器技术解析
  • 【Golang】第五弹----函数
  • go-文件缓存与锁
  • stm32 晶振换算
  • 【蔚蓝星球的节日】世界海洋日的探索与海洋的重要性
  • 【Rust基础】Rust后端开发常用库
  • ssm框架整合
  • 芯科科技推出的BG29超小型低功耗蓝牙®无线SoC,是蓝牙应用的理想之选
  • 哈尔滨算力服务器托管推荐-青蛙云
  • 利用DeepSeek搭建跨工作表数据的可视化分析动态面板
  • VSCode 搭建C++编程环境 2025新版图文安装教程(100%搭建成功,VSCode安装+C++环境搭建+运行测试+背景图设置)
  • 智能三防手持终端破解传统仓储效率困局
  • 每天一道算法题【蓝桥杯】【两两交换链表中的节点】