I get TS error:
TypeScript error: Type 'undefined' cannot be used as an index type. TS2538
For this simple function (getting object from array based on provided index):
const myArr: Array<object> = [{name: 'John'}, {name: 'Tom'}]
function getData(index?: number) {
const isIndex : boolean = typeof index !== 'undefined';
return isIndex ? myArr[index] : {};
}
What's more mysterious for me is that when I change it to:
function getData(index?: number) {
return typeof index !== 'undefined' ? myArr[index] : {};
}
Everything works like a charm - why?