第4章:对象与接口
接口(Interface)的定义与使用
1. 接口的基本概念
接口(Interface)是 TypeScript 的核心特性之一,用于定义对象的形状(Shape)。它描述对象应该包含哪些属性、方法的类型以及它们的结构,但不提供具体实现。接口的主要作用是:
- 为代码定义契约(Contract)
- 提供类型检查的依据
- 增强代码的可读性和可维护性
2. 定义接口
使用 interface 关键字定义接口,语法如下:
interface Person {
name: string;
age: number;
}
3. 使用接口
接口可以用于:
- 变量类型注解
- 函数参数类型
- 函数返回值类型
示例:
// 变量类型注解
const user: Person = {
name: "Alice",
age: 30
};
// 函数参数类型
function greet(person: Person) {
return `Hello, ${person.name}!`;
}
// 函数返回值类型
function createPerson(name: string, age: number): Person {
return { name, age };
}
4. 可选属性
使用 ? 标记可选属性:
interface Config {
url: string;
timeout?: number; // 可选属性
}
5. 只读属性
使用 readonly 标记只读属性:
interface Point {
readonly x: number;
readonly y: number;
}
6. 函数类型
接口可以描述函数类型:
interface SearchFunc {
(source: string, subString: string): boolean;
}
7. 可索引类型
描述可通过索引访问的类型:
interface StringArray {
[index: number]: string;
}
8. 接口 vs 类型别名
与 type 的区别:
- 接口可以扩展(使用
extends) - 接口可以被类实现(
implements) - 同名的接口会自动合并
最佳实践
- 优先使用接口定义对象结构
- 使用清晰、语义化的接口名称
- 保持接口的单一职责
- 考虑将大型接口拆分为多个小接口
示例代码
// 完整接口示例
interface User {
id: number;
username: string;
email?: string;
readonly createdAt: Date;
// 方法定义
getProfile(): string;
}
// 实现接口
const currentUser: User = {
id: 1,
username: "typescript_lover",
createdAt: new Date(),
getProfile() {
return `User: ${this.username}, Joined: ${this.createdAt}`;
}
};
注意:接口是 TypeScript 的编译时特性,不会出现在生成的 JavaScript 代码中。
