My function can work with array and objects. Objects have keys with string-type and array have keys with numeric-type. Also there can be object without keys.
I determine two interfaces and one type:
interface IObjectStringKey {
[key: string]: any
}
interface IObjectNumberKey {
[key: number]: any
}
// object with key-string, key-number or without key
type IObjectAnyKey = IObjectNumberKey | IObjectStringKey | {};
My function get argument - array of this type and I want to iterate through every key of every object.
function myFunction( ...sources: IObjectAnyKey[]) {
const values = [];
for (let i = 0; i < sources.length; i++) {
const source: IObjectAnyKey = sources[i];
for (let key in source) {
const val = source[key];
}
}
}
You can see error in playground: typescript.org/myTask (you need to enable 'noImplicitAny' in Options)
Error is "Element implicitly has an 'any' type because type 'IObjectAnyKey' has no index signature". How can I solve this problem? I need to know how to define type with different index type. Or, maybe, there is some other solve.