interface ts
时间: 2025-02-19 07:03:21 浏览: 27
### TypeScript 接口的定义与使用
接口用于描述对象的形状以及函数参数或返回值的形式。通过接口可以更精确地控制数据结构,提高代码可读性和维护性。
#### 定义简单接口
下面展示如何创建并应用一个简单的 `User` 接口来约束对象属性:
```typescript
// 创建 User 接口
interface IUser {
id: number;
name: string;
}
// 使用该接口声明变量
const user: IUser = {
id: 1,
name: "Alice"
};
```
#### 扩展已有接口
不同于 `type` 声明,`interface` 支持多次声明同一名称从而实现成员追加[^1]:
```typescript
// 初始版本仅含基本字段
interface IBook {
title: string;
}
// 后续增加更多细节而不必重构原有逻辑
interface IBook {
author: string;
yearPublished?: number; // 可选属性
}
```
#### 组合多个现有接口
利用继承机制可以从其他接口派生新的复合类型:
```typescript
// 定义基础组件
interface IPersonalInfo {
firstName: string;
lastName: string;
}
// 构建复杂实体
interface IEmployer extends IPersonalInfo {
company: string;
position: string;
}
```
#### 函数签名中的接口运用
除了静态的数据模型外,还可以用作方法原型说明:
```typescript
// 描述回调行为
interface ISuccessCallback {
(result: boolean): void;
}
function performAction(callback: ISuccessCallback) {
const success = true;
callback(success);
}
```
阅读全文
相关推荐


















