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?
Typescript will not perform code analysis as expected due to an indirection in the code flow. This is when User Defined Type Guards come in to save the day.
function isUndefined(index: any): index is boolean {
return typeof index === "undefined";
}
function getData(index?: number) {
return isUndefined(index) ? myArr[index] : {};
}
Because index is optional in the getData
method, it is possible that it will be undefined
, your second technique works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With