接口基础

接口用于定义对象的类型结构,确保对象具有正确的属性和方法。

基本语法

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

使用接口

变量类型

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

const user: User = {
  id: 1,
  name: "张三",
  email: "zhangsan@example.com"
}

函数参数

function greet(user: User): string {
  return `你好,${user.name}`
}

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

函数返回值

function createUser(name: string, email: string): User {
  return {
    id: Date.now(),
    name,
    email
  }
}

属性检查

缺少属性

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

const user: User = {
  id: 1,
  name: "张三"
  // 错误:缺少 email 属性
}

多余属性

interface User {
  id: number
  name: string
}

const user: User = {
  id: 1,
  name: "张三",
  age: 25  // 错误:多余的属性
}

绕过检查

使用类型断言绕过多余属性检查:

const user = {
  id: 1,
  name: "张三",
  age: 25
} as User

方法定义

方法签名

interface Calculator {
  add(a: number, b: number): number
  subtract(a: number, b: number): number
}

const calc: Calculator = {
  add(a, b) {
    return a + b
  },
  subtract(a, b) {
    return a - b
  }
}

箭头函数语法

interface Calculator {
  add: (a: number, b: number) => number
  subtract: (a: number, b: number) => number
}

实际应用

API 响应

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

interface User {
  id: number
  name: string
}

async function fetchUser(id: number): Promise<ApiResponse<User>> {
  const response = await fetch(`/api/users/${id}`)
  return response.json()
}

配置对象

interface ServerConfig {
  host: string
  port: number
  ssl?: boolean
}

function createServer(config: ServerConfig): void {
  const protocol = config.ssl ? "https" : "http"
  console.log(`服务器启动: ${protocol}://${config.host}:${config.port}`)
}

createServer({ host: "localhost", port: 3000 })

表单数据

interface LoginForm {
  username: string
  password: string
  rememberMe?: boolean
}

function submitForm(data: LoginForm): Promise<void> {
  return fetch("/api/login", {
    method: "POST",
    body: JSON.stringify(data)
  })
}

接口合并

同名接口会自动合并:

interface User {
  name: string
}

interface User {
  age: number
}

const user: User = {
  name: "张三",
  age: 25
}

注意事项

鸭子类型

TypeScript 使用结构化类型系统:

interface Point {
  x: number
  y: number
}

function printPoint(point: Point): void {
  console.log(`(${point.x}, ${point.y})`)
}

const point = { x: 10, y: 20, z: 30 }
printPoint(point)  // 正确:只要包含 x 和 y 就可以

字面量检查

直接传字面量会进行严格检查:

interface User {
  name: string
}

function printUser(user: User): void {
  console.log(user.name)
}

printUser({ name: "张三", age: 25 })  // 错误:多余属性

const user = { name: "张三", age: 25 }
printUser(user)  // 正确:变量赋值不检查多余属性