类型系统设计
Pinia 用 TypeScript 从 defineStore 的返回值 推断 state、getters、actions;Setup store 通过返回类型提取;插件可模块增强 $pinia 与 store 自定义字段。
1. 推断来源
| 定义方式 | 推断方式 |
|---|---|
| Options | state 返回类型、getters/actions 对象 |
| Setup | 函数返回类型整体推断 |
| 插件 | declare module 'pinia' { export interface PiniaCustomProperties … } |
2. 常用导出模式
export const useUserStore = defineStore(...)export type UserStore = ReturnType<typeof useUserStore>
3. storeToRefs 类型
输入 store,输出 state/getters 对应 ref 类型;actions 不在 refs 里。
4. 常见类型问题
| 问题 | 处理 |
|---|---|
| 循环引用 store | 延迟 import 或拆 store |
| 插件注入属性无类型 | 模块增强 |
| Setup 返回联合过宽 | 显式标注返回接口 |
5. 总结
类型设计服务 DX:与运行时解耦,读 store.ts 中泛型辅助类型即可,不必死记每个 Utility Type。