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" }
期望效果
- 未传入PathIds时:
const firebase = new FirebaseService<SomeEntity>() firebase.findOne("someId"); // 合法,不可传入第二个参数 firebase.findOne("someId", { someRandomProp: "" }); // 应报错
- 传入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
相关产品推荐
相关产品推荐

