使用TN-models-fp创建API时遇类型不匹配错误求助
排查TN-models-fp库createApi类型错误
问题重现
使用TN-models-fp库的createApi构建Todo API时,出现以下类型错误:
Type '{ entity: ZodObject<{ id: ZodNumber; title: ZodString; description: ZodString; completed: ZodBoolean; alertTime: ZodDate; createAlert: ZodBoolean; }, "strip", ZodTypeAny, { ...; }, { ...; }>; }' is not assignable to type '"You should not pass `create` model without an `entity` model"'.
相关代码如下:
api.ts
import { axios } from '../axios-instance' import { createApi } from '@thinknimble/tn-models-fp' import { todoShape } from './models' const todoApi = createApi({ baseUri: '/api/todos', client: axios, models: { entity: todoShape, }, })
models.ts
import { z } from 'zod' export const todoShape = z.object({ id: z.number(), title: z.string(), description: z.string(), completed: z.boolean(), alertTime: z.date(), createAlert: z.boolean(), })
错误原因
这个错误是TN-models-fp库类型系统的反向提示,核心问题是传入的models参数结构不符合库的类型约束:
- 库的
createApi函数要求,配置models时必须同时提供entity和create模型(部分版本默认要求CRUD模型的完整性); - 错误提示中的字符串是库用于类型守卫的提示语,说明当前仅传入
entity的models对象,未匹配到预期的类型分支。
解决方法
方法1:补充create模型(推荐)
CRUD场景中,创建实体通常无需传入后端生成的id,可基于现有todoShape创建去掉id字段的create模型:
// models.ts 补充代码 export const todoCreateShape = todoShape.omit({ id: true })
修改api.ts的models配置:
const todoApi = createApi({ baseUri: '/api/todos', client: axios, models: { entity: todoShape, create: todoCreateShape, // 新增create模型 }, })
若需要更新功能,可补充update模型(允许部分字段可选):
// models.ts export const todoUpdateShape = todoCreateShape.partial()
在models中添加update: todoUpdateShape即可。
方法2:检查库版本与官方文档
不同版本的TN-models-fp对models参数的结构要求可能不同,建议确认当前使用版本的文档,查看是否支持仅传入entity模型,或是否有默认生成create/update模型的配置选项。
方法3:显式指定泛型类型
若为类型推断问题,可给createApi显式指定泛型参数,明确Entity和Create类型:
const todoApi = createApi<{ Entity: z.infer<typeof todoShape>, Create: z.infer<typeof todoCreateShape> }>({ baseUri: '/api/todos', client: axios, models: { entity: todoShape, create: todoCreateShape, }, })
内容的提问来源于stack exchange,提问作者Pari Baker
相关产品推荐
相关产品推荐

