必须用interface:当需类implements、声明合并或作为可扩展api入口时;优先用type:当需联合/交叉类型、元组、函数类型或高级类型运算时。

在 TypeScript 中,接口(interface)和类型别名(type)都用于定义对象结构或值的形状,但它们的使用场景、语义和能力略有不同。选哪个不是“对错”问题,而是看需求是否匹配其特性。
用 interface 定义可扩展的契约
interface 更适合描述对象的“对外契约”,尤其当需要支持继承、合并或被类实现时。它天然支持声明合并(多个同名 interface 自动合并为一个),也更符合面向接口编程的思想。
- 用
extends继承其他接口,支持多继承:
interface Admin extends User, Permissions { } - 可以被
class显式实现:
class Staff implements User { name: string; age: number; } - 同名 interface 可多次声明,自动合并(常用于全局增强):
interface String { capitalize(): string; }
interface String { trimEnd(): string; } // 合并后 String 拥有两个方法
用 type 定义灵活的类型组合
type 更通用,能表示联合类型、元组、映射类型、条件类型等复杂结构,不能被类 implements,也不支持声明合并(重复定义会报错)。
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
- 定义联合类型或字面量类型:
type Status = 'loading' | 'success' | 'error';
type ID = string | number; - 定义元组或函数类型:
type Point = [number, number];
type ClickHandler = (e: MouseEvent) => void; - 配合
keyof、in做高级类型操作:
type Keys= keyof T;
type PartialRecord= { [P in K]?: V };
什么时候优先选 interface?
当你在设计公共 API、组件 props、响应数据结构,且预期未来可能被继承、实现或扩展时,interface 是更自然的选择。例如 React 组件的 props、Axios 的响应类型、第三方库的类型声明通常都用 interface。
- 组件 props 接口清晰表达“这个组件接受什么”:
interface ButtonProps { children: string; onClick: () => void; disabled?: boolean; } - 与第三方库配合时(如 Redux、React Router),官方类型大多基于 interface,保持一致性更易维护
什么时候必须用 type?
遇到以下情况只能用 type:
- 需要定义联合类型(
|)、交叉类型(&)或元组:
type ApiResponse = SuccessResponse | ErrorResponse; - 需要给函数类型、原始类型或复杂计算类型起别名:
type AsyncFn= () => Promise ; - 使用映射类型或条件类型(如
Partial<t></t>、ReturnType<f></f>)时,这些本身是 type-level 运算,只能用type包装
不复杂但容易忽略:interface 和 type 在绝大多数对象类型场景下表现一致,编译后都不存在运行时痕迹;真正影响选择的是语义意图和扩展性需求,而不是功能强弱。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










