Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS2538 Type 'undefined' cannot be used as an index type. when check assigned to variable

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?

like image 982
jepek Avatar asked May 29 '19 07:05

jepek


1 Answers

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.

like image 58
Raja Jaganathan Avatar answered Oct 02 '22 13:10

Raja Jaganathan