You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript结合Ramda的prop做校验报ts(2345)错误的解决方法

报错原因

该错误是Ramda工具函数的泛型传参错误,导致TS类型推导链路失效引发的:

  1. prop<K, V>方法的第一个泛型参数指代要读取的属性名类型,你传入了过宽的string类型而非具体的属性字面量类型,相当于告知TS:这个方法会读取目标对象上任意字符串键,要求入参对象必须满足Record<string, string>的索引签名——即所有字符串键对应的值都为string类型。
  2. 你的Calendar类型包含boolean、数组类型的属性,不满足上述索引签名要求,TS最终推导出allPass执行后返回的函数仅能接收Record<string, string> & Record<string, string[]>结构的参数,传入Calendar类型参数时自然触发类型不匹配。报错信息中提到的[Calendar]类型不匹配,是类型推导失败时将单参数误判为元组类型的连带结果。
修复方案

核心是修正泛型参数,让TS可以正确推导类型:

  • 移除prop上错误的宽泛泛型,让TS自动根据传入的属性名推导对应类型,同时给allPass明确传入元组泛型,约束谓词数组的入参类型
  • 如果需要手动标注prop泛型,第一个泛型参数必须传入Calendar上的具体属性字面量类型,不能使用宽泛的string

修复后的代码如下:

export type Calendar = {
  active: boolean;
  businessDay: string[];
  displayName: string;
  holiday: Holiday[];
  label: string;
};

export const isValidCalendar = (calendar: Calendar) =>
  allPass<[Calendar]>([
    pipe(prop('label'), isNil, not),
    pipe(prop('displayName'), isNil, not),
  ])(calendar);

如果需要手动标注prop的泛型,将对应部分替换为prop<'label', string>('label')、prop<'displayName', string>('displayName')即可,效果完全一致。


内容的提问来源于stack exchange,提问作者Enrique Moreno Tent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 04:24:24