I'm trying to use the for in loop over union type of either object or array, since arrays are objects as well and their key property is the index.
const loopOver = (question: any[] | {[key: string]: any} ) => {
for (let key in question) { // error ts 7053
console.log(question[key])
}
};
results in error
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'any[] | { [key: string]: any; }'.
No index signature with a parameter of type 'string' was found on type 'any[] | { [key: string]: any; }'.ts(7053)
but once I remove the union type and leave it to either object or array, then I don't get any errors.
// okay
const loopOver = (question: {[key: string]: any} ) => {
for (let key in question) {
console.log(question[key])
}
};
// okay
const loopOver = (question: any[] ) => {
for (let key in question) {
console.log(question[key])
}
};
tsconfig
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"exclude": ["node_modules"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
}
ts version in package.json ^3.8.3