请教在typescript中动态添加元素的问题?

作者站长头像
站长
· 阅读数 10

代码如下:

type InitPropsType<T> = {
    type: 'load'|'save';
    data: T;
};

type ActionType = {
    load: <T>(data: T) => Promise<T>;
    save: <T>(data: T) => T;
}

const action: ActionType = {
    async load (data) {
        return data;
    },
    save (data) {
        return data;
    }
}

function StorageMethod <T = any> (init: InitPropsType<T>): Promise<T>|T {
    const { type, data } = init;
    return action[type](data);
}

StorageMethod.reload = () => {};
['refresh', 'clear'].forEach(method => {
    StorageMethod[method] = () => {};
});

错误在最后StorageMethod[method],提示如下:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof StorageMethod'. No index signature with a parameter of type 'string' was found on type 'typeof StorageMethod'.

补充说明

  • StorageMethod接收任何类型的数据,所以泛型用了<T = any>
  • 如果指定元素名称,是没有错误的,如StorageMethod.reload = () => {};
  • 如果是动态元素名称,则报错,如:StorageMethod[method]

请问如何修改使其StorageMethod[method]成立?

回复
1个回答
avatar
test
2024-06-30
interface StorageMethod {
  <T>(init: InitPropsType<T>): Promise<T> | T
  reload: () => void
  refresh: () => void
  clear: () => void
}

const storageMethod = <StorageMethod>(<T>(init: InitPropsType<T>) => {
  const { type, data } = init
  return action[type](data)
})

;(['refresh', 'clear', 'reload'] as const).forEach((m) => {
  storageMethod[m] = () => {}
})
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容