一、接口基础概念
接口(interface
)是 TypeScript 的核心类型系统工具,用于定义对象的结构规范。它不关心具体实现细节,只强制要求符合接口定义的对象必须包含指定属性和方法。例如:
interface Person {name: string;age: number;greet(): void;
}
二、核心用法与 API
1.对象类型约束
最基础用法是声明对象形状:
interface User {id: number;username: string;
}
const admin: User = { id: 1, username: "admin" }; // ✅ 符合接口
2.可选属性
通过 ?
声明非必需属性:
interface Config {url: string;timeout?: number; // 可选
}
3.只读属性
用 readonly
防止修改:
interface Point {readonly x: number;readonly y: number;
}
4.函数类型
定义函数签名:
interface SearchFunc {(source: string, keyword: string): boolean;
}
const mySearch: SearchFunc = (src, kw) => src.includes(kw);
5.索引类型
支持动态键值对(数字/字符串索引):
// 数字索引
interface NumMap {[index: number]: string;
}
const arr: NumMap = ["TS", "JS"]; // arr[0]="TS"// 字符串索引
interface StrMap {[key: string]: number;
}
const dict: StrMap = { "A": 65, "B": 66 }; // dict["A"]=65
6.类实现接口
强制类满足特定契约(面向对象):
interface ClockInterface {currentTime: Date;setTime(d: Date): void;
}class Clock implements ClockInterface {currentTime: Date = new Date();setTime(d: Date) { this.currentTime = d; }
}
7.接口继承
支持单继承或多继承:
interface Shape { color: string; }
interface Circle extends Shape { radius: number; }const c: Circle = { color: "red", radius: 10 }; // ✅
8.接口合并
同名接口自动合并(扩展第三方库常用):
interface Box { width: number; }
interface Box { height: number; }
// 合并后: { width: number; height: number; }
三、接口 vs 类型别名(type)
特性 | interface | type |
---|---|---|
扩展方式 | 继承(extends ) | 交叉类型(& ) |
合并同名声明 | ✅ 自动合并 | ❌ 报错 |
函数/元组定义 | ✅ 支持 | ✅ 支持 |
声明合并 | ✅ | ❌ |
实现类 | ✅ implements | ❌ 仅对象类型 |
最佳实践:优先使用
interface
定义对象结构,用type
处理联合类型或复杂类型运算。
四、高级技巧
1.混合类型
组合函数和对象属性:
interface Counter {(start: number): void;interval: number;reset(): void;
}
2.索引签名约束
限制索引值类型必须匹配特定属性:
interface Foo {[key: string]: number;bar: number; // ✅// baz: string; ❌ 违反索引签名
}
五、常见错误解决方案
属性缺失错误 → 检查是否遗漏必需属性或误用可选属性
类型不匹配错误 → 确认属性类型是否精确符合接口定义
索引签名冲突 → 确保所有显式属性符合索引签名类型
接口的核心价值在于 定义契约 而非实现,这是构建可维护大型项目的关键。