My current situation involves an object type:
interface ShortUrlParam {
openid: string;
avatar: string;
nickname: string;
}
const param: ShortUrlParam = {
openid: 'abc123',
avatar: '',
nickname: 'wenzi'
}
let query = '';
for(let key in param) {
query += `&${key}=${encodeURIComponent(param[key])}`; // encountering an error here
}
When accessing param[key], I receive the following error message:
'Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ShortUrlParam'. No index signature with a parameter of type 'string' was found on type 'ShortUrlParam'.ts(7053)
I have come up with two potential solutions, both not without flaws.
1. Redefining the interface ShortUrlParam
interface ShortUrlParam {
openid: string;
avatar: string;
nickname: string;
[key: string]: string;
}
2. Treating param as any
for(let key in param) {
query += `&${key}=${encodeURIComponent((param as any)[key])}`;
}
My inquiry is whether there exists a more optimal solution to this issue?