Vue / 系统课时

对象类型与接口

对象类型与接口

本课使用商品与订单场景演示如何通过对象类型、interface 和 type 描述业务数据。完成后,你能够为 Vue 组件属性、接口响应和业务函数建立稳定契约,并正确处理可选、只读和组合类型。

学习目标

  • 使用 interface 描述具有固定字段的业务对象
  • 使用 type 表达联合类型、交叉类型和函数类型
  • 掌握可选属性、只读属性与类型组合的边界

使用 interface 描述业务对象

对象类型用于约束对象必须包含哪些字段,以及每个字段允许保存什么数据。对于商品、用户、订单等可扩展的实体结构,通常优先使用 interface。

ts
interface Product {
  readonly id: number
  name: string
  price: number
  description?: string
}

function formatProduct(product: Product): string {
  const description = product.description ?? '暂无描述'
  return `${product.id} - ${product.name} - ${product.price} 元 - ${description}`
}

const keyboard: Product = {
  id: 1001,
  name: '机械键盘',
  price: 399
}

console.log(formatProduct(keyboard))

预期输出:

text
1001 - 机械键盘 - 399 元 - 暂无描述

readonly id 表示对象创建后不能重新分配编号,适合数据库主键和业务流水号。description? 表示字段可以不存在,读取时需要准备默认值或进行条件判断。

使用 type 表达组合关系

type 不仅能描述对象,还能为联合类型、交叉类型、元组和函数签名建立别名。当一个类型需要表达多个候选值或组合已有类型时,type 通常更直观。

ts
type OrderStatus = 'pending' | 'paid' | 'cancelled'

type TimestampFields = {
  createdAt: string
  updatedAt: string
}

type Order = TimestampFields & {
  id: string
  productId: number
  quantity: number
  status: OrderStatus
}

type PriceCalculator = (price: number, quantity: number) => number

const calculatePrice: PriceCalculator = (price, quantity) => price * quantity

const order: Order = {
  id: 'ORDER-10001',
  productId: 1001,
  quantity: 2,
  status: 'paid',
  createdAt: '2026-08-03T03:00:00Z',
  updatedAt: '2026-08-03T03:05:00Z'
}

console.log(order.status)
console.log(calculatePrice(399, order.quantity))

预期输出:

text
paid
798

OrderStatus 将状态限制为三个合法字符串,能够阻止拼写错误。交叉类型 TimestampFields & {...} 把公共时间字段与订单字段合并,适合复用稳定且独立的数据片段。

interface 与 type 的选择

两者都能描述普通对象,但侧重点不同。

场景 推荐写法 原因
组件 Props、业务实体 interface 结构清晰,支持继承和声明合并
字符串状态集合 type 可以直接声明联合类型
函数签名或元组 type 表达方式更紧凑
组合多个已有类型 type 交叉类型便于复用

项目中不必强制所有对象只使用一种写法。更重要的是保持同一模块风格一致,并让类型名称准确表达业务含义。

为组件属性建立契约

下面是 Vue 3 <script setup> 中的片段示例,需要放入 .vue 单文件组件,并由 Vue 编译器处理。

ts
interface ProductCardProps {
  product: Product
  selected?: boolean
  onSelect: (productId: number) => void
}

const props = withDefaults(defineProps<ProductCardProps>(), {
  selected: false
})

props.onSelect(props.product.id)

product 是必传业务对象,selected 是带默认值的可选属性,onSelect 则约束回调必须接收商品编号。验证时,父组件缺少必填属性、传入错误字段类型或提供不兼容的回调函数,TypeScript 与 Vue 插件都会在编辑器或构建阶段报告错误。

不要为了复用而创建包含大量可选字段的“万能接口”。当创建、详情和更新接口所需字段不同,应分别建立类型,或使用 Pick、Omit、Partial 等工具类型从基础模型派生。

ts
type CreateProductInput = Omit<Product, 'id'>
type UpdateProductInput = Partial<Pick<Product, 'name' | 'price' | 'description'>>

这是类型定义片段,不会产生运行时输出。它的生效行为是:创建商品时禁止传入 id,更新商品时只允许提交指定字段,并且这些字段都可以省略。

本课总结

  • interface 适合描述可扩展的组件属性和业务实体结构
  • type 适合联合类型、函数签名以及多个类型的组合
  • 可选与只读修饰符应反映真实业务规则,不应被用来回避数据建模

下一课预告

下一课将继续学习泛型,通过可复用的类型参数描述接口响应、列表数据和通用组件。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

对象类型与接口

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通