【发布时间】:2021-08-15 15:51:06
【问题描述】:
我对 TS 还很陌生,一直被这个特定问题所困扰。
我正在使用 reduce 构建一个对象,它将对象方法包装在一个函数中。我需要对象返回原始对象的键以及 apiDispatch 函数的承诺,据我所知。
任何帮助将不胜感激
const actions = {
getSomething: ({ id }) => ({
url: `/something/${id}`
})
};
function buildClient() {
const apiDispatch = async (data: any) => Promise;
return Object.entries(actions).reduce((acc, [key, value]) => {
acc[key] = (data: any, options: any): Promise<any> =>
apiDispatch({
...value(data),
...options
});
return acc;
}, {} as typeof actions);
}
const client = buildClient();
client.getSomething({ id: 123 }).then((res: any) => res);
-
acc[key]给出以下错误 -Element implicitly has an 'any' type because expression of type 'string' can't be used to index type -
client.getSomething().then()then 没有赋值给类型
codeandbox 链接:
https://codesandbox.io/s/typescript-playground-export-forked-2yg63?file=/index.ts
【问题讨论】:
-
您可以像这样使用
actions: Record<string, any>指定操作类型:codesandbox.io/s/… 有帮助吗?
标签: typescript typescript-typings