TypeScript中如何声明动态对象的递归方法链式调用类型
解决方案
核心思路是单独抽离myFunc返回值的类型,避免this指向外层的Obj类型,同时补全方法参数的类型定义。
步骤1:定义myFunc返回值的专用类型
// 映射类型:每个键对应方法返回同类型对象,实现链式调用 type MyFuncReturn<T extends Record<string, any>> = { [K in keyof T]: (val: T[K]) => MyFuncReturn<T> }
步骤2:声明myFunc的函数类型
declare function myFunc<T extends Record<string, any>>(props: T): MyFuncReturn<T>;
步骤3:定义外层Obj泛型类型
type Obj<T extends Record<string, any>> = { // 注意:obj.myFunc是myFunc执行后的返回值,不是函数类型,不需要加() => myFunc: MyFuncReturn<T>; anotherFunc: () => void; moreFunc: () => void; }
步骤4:实际使用绑定类型
const myProps = { counter: 0, isCounting: false, } // 绑定泛型参数为myProps的类型即可 const obj: Obj<typeof myProps> = { myFunc: myFunc(myProps), anotherFunc: () => {}, moreFunc: () => {}, }
效果验证
此时调用链式方法obj.myFunc.counter(1).isCounting(true)时,只会提示counter、isCounting两个方法,不会出现外层的anotherFunc等多余属性,且方法参数会自动匹配myProps对应字段的类型,完全符合预期。
内容的提问来源于stack exchange,提问作者user12499410
相关产品推荐
相关产品推荐

