使用动态变量ts报错的解决
# 使用动态变量ts报错的解决
# TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.
export const cleanObject = (object: object) => {
const result = { ...object };
for (const [key, val] of Object.entries(result)) {
if (!val) {
delete result[key]; // result[key]报错,具有隐性any
}
}
return result;
};
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 解决
export const cleanObject = (object: object) => {
type Result = {
[key: string]: any;
};
const result: Result = { ...object };
for (const [key, val] of Object.entries(result)) {
if (!val) {
delete result[key];
}
}
return result;
};
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
上次更新: 3/2/2022, 6:42:33 PM