接口

接口是 TypeScript 的核心特性之一,用于定义对象的形状、函数类型、类结构等。接口提供了一种强大的方式来定义契约。

什么是接口

接口定义了一组属性和方法的规范,任何实现该接口的对象都必须遵循这个规范。

interface User {
  id: number
  name: string
  email: string
}

function printUser(user: User): void {
  console.log(`${user.name} <${user.email}>`)
}

printUser({ id: 1, name: "张三", email: "zhangsan@example.com" })

接口的作用

类型检查

interface Product {
  id: number
  name: string
  price: number
}

const product: Product = {
  id: 1,
  name: "苹果",
  price: 5,
  stock: 100  // 错误:多余的属性
}

代码契约

interface Repository<T> {
  findById(id: number): Promise<T | null>
  save(entity: T): Promise<T>
  delete(id: number): Promise<void>
}

文档作用

interface ApiResponse<T> {
  code: number
  message: string
  data: T
  timestamp: number
}

接口特性

特性说明
可选属性使用 ? 标记
只读属性使用 readonly 修饰
函数类型定义函数签名
可索引类型定义索引签名
类类型定义类的结构
接口继承使用 extends 继承

本章节内容

文章说明
接口基础基本定义和使用
可选属性可选的属性定义
只读属性不可修改的属性
函数类型接口定义函数类型
可索引类型数组和字典类型
类类型接口定义类的结构
接口继承接口的继承关系

接口 vs 类型别名

// 接口
interface User {
  name: string
  age: number
}

// 类型别名
type UserType = {
  name: string
  age: number
}

主要区别:

特性接口类型别名
可以被扩展
可以被实现
声明合并支持不支持
联合类型不支持支持
元组类型不支持支持

最佳实践

优先使用接口

对于对象类型,优先使用接口:

interface User {
  id: number
  name: string
}

类型别名用于联合类型

type Status = "pending" | "approved" | "rejected"
type ID = string | number

命名规范

// 接口使用 PascalCase
interface UserProfile {}

// 类型别名也使用 PascalCase
type UserRole = "admin" | "user"