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 同名接口自动合并
相关推荐
yingyima17 分钟前
正则表达式实战:从日志中精准提取关键字段
前端
TeamDev25 分钟前
如何在 DotNetBrowser 中使用本地 AI 模型
前端·后端·.net
谢尔登43 分钟前
10_从 React Hooks 本质看 useState
前端·ubuntu·react.js
辰同学ovo1 小时前
从全局登录状态管理学习 Redux
前端·javascript·学习·react.js
陈随易1 小时前
2年没用Nodejs了,Bun很香
前端·后端·程序员
donecoding1 小时前
Corepack 完全解析:从懵到懂,包管理器自由了
前端·node.js·前端工程化
yqcoder1 小时前
端经典面试题:为什么 0.1 + 0.2 !== 0.3?
前端·css
ZC跨境爬虫2 小时前
跟着 MDN 学 HTML day_12:(HTML网页图片嵌入)
前端·javascript·css·ui·html
knight_9___2 小时前
LLM工具调用面试篇5
人工智能·python·深度学习·面试·职场和发展·llm·agent
光影少年2 小时前
reeact虚拟DOM、Diff算法原理、key的作用与为什么不能用index
前端·react.js·掘金·金石计划