Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'undefined' cannot be used as index type

I am following WintellectNow React with TypeScript Tutorial. In the fifth part Sorting and filtering the author creates an interface with optional properties like below :

interface IWidgetToolState {
   filterCol?: WidgetTableCols;
   filterValue?: string;
   sortCol?: WidgetTableCols;
}

There is an enum called WidgetTableCols as below :

enum WidgetTableCols {
    None, Name, Color, Size, Quantity, Price,
}

In a function the author gets the value of enum like this :

const fName: string = 
WidgetTableCols[this.state.sortCol].toLocaleLowerCase();

Here I am getting Type undefined cannot be used as an index type. If I remove ? from the interface it works but later the author creates another function that only sets one of the state values and TypeScript says not all of the state properties are set.

Can anybody let me know how to solve this issue?

like image 654
Abhilash D K Avatar asked May 07 '17 20:05

Abhilash D K


People also ask

Can not be used as an index type?

The error "Type cannot be used as an index type" occurs when we try to use a type that cannot be used to index an array or object, e.g. one of the non-primitive types like String . To solve the error, use primitive (lowercase) types, e.g. number or string when typing values.

How do you fix possibly undefined object?

The "Object is possibly 'undefined'" error occurs when we try to access a property on an object that may have a value of undefined . To solve the error, use the optional chaining operator or a type guard to make sure the reference is not undefined before accessing properties.


1 Answers

The compiler just tells you that this.state.sortCol might not have a value because you have the strictNullChecks flag on.

You can first check for its existence:

const fName = this.state.sortCol != null ?  WidgetTableCols[this.state.sortCol].toLocaleLowerCase() : null; 

Which will remove the error (but you will then need to deal with the fact that fName can be null).

You can also use the Non-null assertion operator:

const fName: string =  WidgetTableCols[this.state.sortCol!].toLocaleLowerCase(); 

If you're sure that it exists.

like image 95
Nitzan Tomer Avatar answered Sep 20 '22 12:09

Nitzan Tomer