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?
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.
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.
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.
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