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

TypeScript中根据泛型是否存在设置函数参数必填性

问题描述

我正在开发适配Firebase嵌套集合的FirebaseService类,需要优化findOne方法的参数逻辑:

  • 指定泛型PathIds时,pathArgs参数必须传入且类型匹配PathIds
  • 未指定PathIds时,pathArgs参数不允许传入
现有代码
class FirebaseService<T, PathIds = {}> {
    public findOne(id: string, pathArgs?: PathIds): T { return {} as T };
}

type SomeEntity = {
    hello: "hello"
}
期望效果
  1. 未传入PathIds时:
const firebase = new FirebaseService<SomeEntity>()
firebase.findOne("someId"); // 合法,不可传入第二个参数
firebase.findOne("someId", { someRandomProp: "" }); // 应报错
  1. 传入PathIds时:
const firebase = new FirebaseService<SomeEntity, { userId: string }>()
firebase.findOne("someId"); // 应报错,需传入符合类型的第二个参数
firebase.findOne("someId", { userId: "" }); // 合法
当前遇到的问题

已找到初步解决方案,但内部代码出现类型错误:

Argument of type '[PathArgs<P>]' is not assignable to parameter of type 'PathArgs<P>'

外部调用逻辑正常,仅内部代码报此错误。

内容的提问来源于stack exchange,提问作者Darkbound

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 03:05:49