TypeScript 接口
最后修改于 2025 年 2 月 25 日
TypeScript 中的接口用于定义对象的结构。它们允许您指定对象的形状,包括它应该具有的属性和方法。本教程涵盖 TypeScript 接口的创建、用法和实际示例。
接口是 TypeScript 中定义自定义类型的一种方式。它们描述了对象的形状,包括其属性和方法的名称和类型。接口纯粹是编译时构造,不会生成任何 JavaScript 代码。
基本接口
此示例演示了如何创建和使用基本接口。
basic_interface.ts
interface Person {
name: string;
age: number;
}
let user: Person = {
name: "Alice",
age: 30
};
console.log(user); // Output: { name: "Alice", age: 30 }
Person 接口定义了一个具有 name 和 age 属性的对象的结构。user 对象符合此接口。
可选属性
此示例演示了如何在接口中定义可选属性。
optional_properties.ts
interface Person {
name: string;
age?: number; // Optional property
}
let user1: Person = {
name: "Alice"
};
let user2: Person = {
name: "Bob",
age: 25
};
console.log(user1); // Output: { name: "Alice" }
console.log(user2); // Output: { name: "Bob", age: 25 }
age 属性使用 ? 符号标记为可选。这允许对象在不包含 age 属性的情况下仍然符合 Person 接口。
只读属性
此示例演示了如何在接口中定义只读属性。
readonly_properties.ts
interface Person {
readonly id: number;
name: string;
}
let user: Person = {
id: 1,
name: "Alice"
};
// user.id = 2; // Error: Cannot assign to 'id' because it is a read-only property.
console.log(user); // Output: { id: 1, name: "Alice" }
id 属性被标记为只读,这意味着在创建对象后无法修改它。这确保了特定属性的不可变性。
接口中的函数类型
此示例演示了如何在接口中定义函数类型。
function_types.ts
interface GreetFunction {
(name: string): string;
}
let greet: GreetFunction = (name) => {
return `Hello, ${name}!`;
};
console.log(greet("Alice")); // Output: Hello, Alice!
GreetFunction 接口定义了一个函数类型,该类型接受一个 string 参数并返回一个 string。greet 函数符合此接口。
扩展接口
此示例演示了如何扩展接口以创建新接口。
extending_interfaces.ts
interface Person {
name: string;
age: number;
}
interface Employee extends Person {
employeeId: number;
}
let employee: Employee = {
name: "Alice",
age: 30,
employeeId: 12345
};
console.log(employee); // Output: { name: "Alice", age: 30, employeeId: 12345 }
Employee 接口扩展了 Person 接口,并添加了 employeeId 属性。这实现了可重用和模块化的类型定义。
可索引类型
此示例演示了如何在接口中定义可索引类型。
indexable_types.ts
interface StringArray {
[index: number]: string;
}
let fruits: StringArray = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Output: Apple
StringArray 接口定义了一种可索引类型,其中索引是 number,值是 string。这实现了具有类型安全的类数组结构。
使用接口的最佳实践
- 使用描述性名称:为接口选择有意义的名称以提高代码的可读性。
- 保持接口精简:定义小型、聚焦的接口以促进可重用性和模块化。
- 利用可扩展性:使用接口继承来创建可重用和模块化的类型定义。
- 记录接口:添加注释或文档来解释自定义接口的用途。
来源
在本文中,我们探讨了 TypeScript 接口并通过实际示例演示了它们的使用。