TypeScript 中的接口(interface
)是定义对象类型的一种强大工具。它不仅可以用于定义对象的结构,还可以用于描述函数类型、类的结构以及与其他类型的兼容性。下面是 TypeScript 中接口的详细介绍,包括其用途、特性和示例代码。
1. 基础语法
定义接口
接口用来定义对象的结构,包括属性和方法。例如:
interface Person {
name: string;
age: number;
}
这个接口定义了一个 Person
类型,包含 name
和 age
两个属性。
使用接口
你可以使用接口来创建符合该结构的对象:
const person: Person = {
name: 'Alice',
age: 30
};
2. 可选属性
接口中的属性可以是可选的,用 ?
表示:
interface Person {
name: string;
age?: number; // age 是可选的
}
const person1: Person = {
name: 'Bob'
};
const person2: Person = {
name: 'Charlie',
age: 25
};
3. 只读属性
接口中的属性可以是只读的,用 readonly
修饰:
interface Person {
readonly id: number;
name: string;
}
const person: Person = {
id: 1,
name: 'Dave'
};
person.name = 'Eve'; // 允许
person.id = 2; // 错误:只读属性 'id' 不能赋值
4. 函数类型
接口可以用来定义函数类型:
interface GreetFunction {
(name: string): string;
}
const greet: GreetFunction = (name: string) => `Hello, ${name}!`;
console.log(greet('Frank')); // 输出: Hello, Frank!
5. 索引签名
如果你不知道对象的所有属性名,但知道属性值的类型,可以使用索引签名:
interface Dictionary {
[key: string]: number;
}
const dict: Dictionary = {
'apple': 1,
'banana': 2
};
dict['cherry'] = 3; // 允许
6. 接口的继承
接口可以继承其他接口,合并其属性和方法:
interface Animal {
name: string;
}
interface Bird extends Animal {
fly(): void;
}
const sparrow: Bird = {
name: 'Sparrow',
fly: () => console.log('Flying')
};
7. 类实现接口
类可以实现接口,确保类符合接口的结构:
interface Animal {
name: string;
makeSound(): void;
}
class Dog implements Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound(): void {
console.log('Woof!');
}
}
const dog = new Dog('Rex');
console.log(dog.name); // Rex
dog.makeSound(); // Woof!
8. 接口与类型别名的比较
interface
和 type
都可以用来定义对象类型,但它们有一些区别:
- 接口:主要用于定义对象的结构。可以被合并和扩展,适合描述类的结构和对象类型。
- 类型别名(
type
):更灵活,可以用于联合类型、交叉类型等。不能像接口那样进行扩展和合并,但在描述复杂类型时更有用。
示例:
type Point = { x: number; y: number };
interface Point2D {
x: number;
y: number;
}
// 这两者是等效的
const point1: Point = { x: 1, y: 2 };
const point2: Point2D = { x: 1, y: 2 };
9. 接口合并
TypeScript 支持接口的合并(即同名接口会合并):
interface Animal {
name: string;
}
interface Animal {
age: number;
}
const animal: Animal = {
name: 'Lion',
age: 5
};
10. 高级用法
泛型接口
接口支持泛型,使其更具灵活性:
interface Response<T> {
data: T;
status: number;
}
const response: Response<string> = {
data: 'Hello, world!',
status: 200
};
条件类型
接口与条件类型结合使用,提供强大的类型操作能力:
type Response<T> = T extends 'success' ? { data: any } : { error: string };
type SuccessResponse = Response<'success'>; // { data: any }
type ErrorResponse = Response<'error'>; // { error: string }