TypeScript 中 interface 和 type 的区别

在 TypeScript 中,interfacetype 都用于定义类型,但它们有一些关键区别。今天我们就来详细对比它们的特性、使用场景和注意事项,帮你彻底掌握这两个核心概念!


核心区别对比表

特性 interface type
扩展性 支持 extendsimplements 支持交叉类型(&
合并声明 同名接口会自动合并 同名类型会报错
适用场景 定义对象形状、类实现 复杂类型(联合、元组、条件类型等)
兼容性 更适合面向对象编程 更灵活,适合函数式编程
示例 interface User { name: string } type User = { name: string }

详细解析

1. 扩展与继承

interface :通过 extends 扩展其他接口。

typescript 复制代码
interface Person {
  name: string;
}
interface User extends Person {
  id: number;
}

type :通过交叉类型(&)扩展。

ini 复制代码
type Person = {
  name: string;
};
type User = Person & { id: number };

2. 合并声明

interface:同名接口会自动合并。

kotlin 复制代码
interface User { name: string; }
interface User { age: number; }
// 最终 User 包含 name 和 age

type:同名类型会报错。

ini 复制代码
type User = { name: string; };
type User = { age: number; }; // 报错:重复声明

3. 适用场景

interface 更适合

  • 定义对象的形状(如 API 响应)。

类的实现(implements)。

typescript 复制代码
interface Animal {
  eat(): void;
}
class Dog implements Animal {
  eat() { console.log("Eating..."); }
}

type 更适合

定义联合类型、元组、条件类型等复杂类型。

typescript 复制代码
// 联合类型
type Status = "success" | "error";
// 元组
type Point = [number, number];
// 条件类型
type IsString<T> = T extends string ? true : false;

4. 其他区别

type 可以定义原始类型

typescript 复制代码
type ID = number | string

interface 可以声明类实例的类型

typescript 复制代码
interface ClockInterface {
  currentTime: Date;
}
class Clock implements ClockInterface {
  currentTime: Date = new Date();
}

如何选择?

  • 默认情况下 :优先使用 interface(更适合面向对象编程)。
  • 需要复杂类型时 :使用 type(如联合类型、条件类型)。
  • 需要合并声明时 :使用 interface

总结

场景 推荐使用 示例
定义对象形状 interface interface User { name: string }
类实现 interface class X implements Y {}
联合类型/复杂类型 type `type ID = string number`
需要合并声明 interface 同名接口自动合并
相关推荐
打小就很皮...27 分钟前
HBuilder 发行Android(apk包)全流程指南
前端·javascript·微信小程序
集成显卡1 小时前
PlayWright | 初识微软出品的 WEB 应用自动化测试框架
前端·chrome·测试工具·microsoft·自动化·edge浏览器
前端小趴菜052 小时前
React - 组件通信
前端·react.js·前端框架
Amy_cx3 小时前
在表单输入框按回车页面刷新的问题
前端·elementui
dancing9993 小时前
cocos3.X的oops框架oops-plugin-excel-to-json改进兼容多表单导出功能
前端·javascript·typescript·游戏程序
后海 0_o3 小时前
2025前端微服务 - 无界 的实战应用
前端·微服务·架构
Scabbards_3 小时前
CPT304-2425-S2-Software Engineering II
前端
小满zs3 小时前
Zustand 第二章(状态处理)
前端·react.js
程序猿小D3 小时前
第16节 Node.js 文件系统
linux·服务器·前端·node.js·编辑器·vim
萌萌哒草头将军3 小时前
🚀🚀🚀Prisma 发布无 Rust 引擎预览版,安装和使用更轻量;支持任何 ORM 连接引擎;支持自动备份...
前端·javascript·vue.js