代码如下:
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]