使用Typescript和Proxy修改函数对象中的参数



我正试图修改第三方生成的对象,以获得更好的开发人员体验,因为生成的对象中的一些参数不再需要/可以在默认情况下在使用它的地方进行设置。尽管我仍然希望在调用我的钩子以给出该对象中可用方法的建议时,将IntelliSense保持在typescript中。

type ObjectFunction<Type> = Type extends (_: { prop: infer MessageType }, __: infer CallbackType) => infer Return
? (prop?: MessageType, callback?: CallbackType) => Return
// trying to simplify the argument above
: never;
type NewObjectType<Type> = {
[Property in keyof Type as ObjectFunction<Type[Property]> extends never ? never : Property]: ObjectFunction<
Type[Property]
>;
};

下面是我试图在我的挂钩中代理它

return new Proxy<NewObjectType<typeof originalObj>>(
{ ...originalObj },
// typescript will error above as the shape is different thru the NewObjectType and the orignalObj
{
get(target, method) {
if (typeof method === "string" && target.hasOwnProperty(method)) {
return target[method as keyof NewObjectType<typeof originalObj>];
}
},
},
);

下面是我想要实现的一个例子

originalObj = {
method1: (arg: {prop: string}, callback?: ()=> void) => void
method2: (arg: {prop: string}, callback?: ()=> void) => void
...
}

进入以下

newObj = {
method1: (prop?: string, callback?: ()=> void) => void
method2: (prop?: string, callback?: ()=> void) => void
...
}

这里没有代理的理由。您的代理似乎不起作用,它返回原始方法,而不是直接接受prop字符串的方法。

我建议简单地写

const newObj = {} as NewObjectType<typeof originalObj>;
for (const name in originalObj) {
newObj[name] = (prop, callback) => originalObj[name]({prop}, callback);
}
return newObj;

最新更新