Я пытаюсь использовать for in loop
для типа объединения объекта или массива, поскольку массивы также являются объектами, а их ключевое свойство является индексом.
const loopOver = (question: [] | {[key: string]: any} ) => {
for (let key in question) { // error ts 7053
console.log(question[key])
}
};
приводит к ошибке
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ [key: string]: any; } | []'.
No index signature with a parameter of type 'string' was found on type '{ [key: string]: any; } | []'.ts(7053)
но как только я удаляю тип объединения и оставляю его объекту или массиву, я не получаю никаких ошибок.
// okay
const loopOver = (question: {[key: string]: any} ) => {
for (let key in question) {
console.log(question[key])
}
};
// okay
const loopOver = (question: [] ) => {
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 версия в упаковке. json ^3.8.3