TypeScript泛型函数报错:'{ id: string; }'无法赋值给DeepPartial<T>
问题:TypeScript泛型函数中DeepPartial类型不兼容错误
我尝试编写泛型函数抽象仓库基础设施以生成where子句,代码如下:
export type DeepPartial<T> = T extends object ? { [P in keyof T]?: DeepPartial<T[P]>; } : T; export interface SearchOneOptions<ENTITY extends { id: string }> { /** Names of object attributes nested in the result object that must be filled, if possible */ includeNested?: string[]; /** Entities that can be soft deleted won't appear in queries by default */ withDeleted?: boolean; select?: string[]; where?: DeepPartial<ENTITY> } const b = <T extends { id: string }>(t: T) => { const a: SearchOneOptions<T> = { where: { id: t.id } } }
运行时遇到错误:Type '{ id: string; }' is not assignable to type 'DeepPartial<T>'.
问题原因
TypeScript无法确认{ id: t.id }与DeepPartial<T>完全兼容:因为T可以是{ id: string }的子类型(比如字面量类型{ id: 'user-123' }),此时DeepPartial<T>的id属性类型是'user-123' | undefined,但{ id: t.id }会被TypeScript推断为{ id: string },与字面量类型不匹配,导致类型错误。
解决方法
方法1:使用类型断言
直接将{ id: t.id }断言为DeepPartial<T>,明确告诉TypeScript该结构符合目标类型:
const b = <T extends { id: string }>(t: T) => { const a: SearchOneOptions<T> = { where: { id: t.id } as DeepPartial<T> } }
方法2:通过辅助函数推导类型
创建辅助函数生成where子句,让TypeScript自动完成类型匹配:
const createIdWhere = <T extends { id: string }>(t: T): DeepPartial<T> => ({ id: t.id }); const b = <T extends { id: string }>(t: T) => { const a: SearchOneOptions<T> = { where: createIdWhere(t) } }
方法3:调整SearchOneOptions的where类型(按需选择)
如果不需要嵌套结构的部分匹配,可以将where的类型改为Partial<ENTITY>(代替DeepPartial<ENTITY>),这样TypeScript能直接推断{ id: t.id }的兼容性:
export interface SearchOneOptions<ENTITY extends { id: string }> { // ...其他属性 where?: Partial<ENTITY> }
内容的提问来源于stack exchange,提问作者Ricardo Rodriguez
相关产品推荐
相关产品推荐

