35

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?

2
  • 2
    Are you using strictNullChecks? May 7, 2017 at 20:52
  • Yes strictNullChecks is true. I changed it to false. Now its working. May 7, 2017 at 20:54

1 Answer 1

57

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.

5
  • Thanks for the explanation. Will go with non null assertion operator. May 7, 2017 at 21:20
  • 4
    Javascript allows undefined to be used as an index type. So the following works: x = {}; x[undefined] = 3; Why doesn't typescript allow it?
    – Aaron
    Sep 4, 2017 at 19:12
  • 13
    @Aaron in js keys of objects are always strings, when you're doing this x[undefined] = 3; you are basically getting this x["undefined"] = 3;. Typescript just forces you to acknowledge that. Sep 4, 2017 at 20:05
  • 4
    Why would this situation occur even if you have strict checks beforehand? i.e. if (this.state.sortCol && !!this.state.sortCol && etc..) WidgetTableCols[this.state.sortcol] ? Jun 1, 2021 at 11:42
  • Honestly I disagree with Typescript here. Undefined and null CAN be used as index, they just get cast to string. The same is true for numbers. For example x[4] = 'something' works just fine but here 4 is also cast to string and is the same as x['4'] = 'something'. I don't understand why it would be different for null and undefined.
    – Marnix
    Feb 17 at 12:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.