在 TypeScript 中,接口(Interface)是一种用于定义对象结构的类型。接口可以描述对象的属性、方法、函数类型、索引签名等。通过接口,你可以确保对象符合特定的结构,从而提高代码的可读性和可维护性。
定义接口的基本语法
interface InterfaceName {
property1: type1;
property2: type2;
method1(param1: type3): returnType;
// 更多属性和方法
}
示例
1. 定义简单接口
以下是一个简单的接口示例,描述了一个具有 name
和 age
属性的对象:
interface Person {
name: string;
age: number;
}
const person: Person = {
name: "Alice",
age: 25
};
2. 定义带有方法的接口
接口不仅可以描述属性,还可以描述方法。以下是一个带有方法的接口示例:
interface Greetable {
name: string;
greet(phrase: string): void;
}
class Person implements Greetable {
name: string;
constructor(name: string) {
this.name = name;
}
greet(phrase: string) {
console.log(`${phrase} ${this.name}`);
}
}
const person = new Person("Alice");
person.greet("Hello"); // 输出: Hello Alice
3. 定义可选属性
接口中的属性可以是可选的,使用 ?
符号表示:
interface Person {
name: string;
age?: number; // age 是可选的
}
const person1: Person = {
name: "Alice"
};
const person2: Person = {
name: "Bob",
age: 30
};
4. 定义只读属性
接口中的属性可以是只读的,使用 readonly
关键字表示:
interface Person {
readonly id: number;
name: string;
}
const person: Person = {
id: 1,
name: "Alice"
};
person.name = "Bob"; // OK
person.id = 2; // Error: Cannot assign to 'id' because it is a read-only property.
5. 定义函数类型
接口不仅可以描述对象,还可以描述函数类型:
interface SearchFunc {
(source: string, subString: string): boolean;
}
const mySearch: SearchFunc = function(source: string, subString: string) {
return source.search(subString) > -1;
};
console.log(mySearch("hello world", "world")); // 输出: true
6. 定义索引签名
接口可以定义索引签名,用于描述可以通过索引访问的对象:
interface StringArray {
[index: number]: string;
}
const myArray: StringArray = ["Alice", "Bob"];
const firstItem: string = myArray[0]; // "Alice"
7. 定义接口继承
接口可以继承其他接口,从而组合多个接口的属性:
interface Person {
name: string;
}
interface Employee extends Person {
employeeId: number;
}
const employee: Employee = {
name: "Alice",
employeeId: 1234
};
8. 定义混合类型
接口可以描述混合类型,即对象可以同时作为函数和对象使用:
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
function getCounter(): Counter {
let counter = function(start: number) {} as Counter;
counter.interval = 123;
counter.reset = function() {};
return counter;
}
const c = getCounter();
c(10);
c.reset();
c.interval = 5.0;
总结
接口是 TypeScript 中用于定义对象结构的重要工具。通过接口,你可以描述对象的属性、方法、函数类型、索引签名等。接口还可以继承其他接口,从而组合多个接口的属性。理解如何定义和使用接口,可以帮助你编写出更安全、更易维护的代码。