当前位置: 首页 > 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 处理复杂类型。

相关文章:

  • 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-文件缓存与锁
  • 巴西商业农场首次确诊高致病性禽流感,中国欧盟暂停进口巴西禽肉产品
  • 王楚钦球拍受损,乒乓球裁判揭秘大赛球拍检测
  • 上海发布台风红色预警?实为演练,今日下午局部中雨下班请注意
  • 金融监管总局将研究出台专门的城市更新项目贷款管理办法:引导大力支持城中村的改造等
  • 俄罗斯哈巴罗夫斯克市首次举办“俄中论坛”
  • 63岁微波遥感领域著名专家李春升参加学术会议期间病逝