类型“未定义"不能用作索引类型 [英] Type 'undefined' cannot be used as index type

查看:46
本文介绍了类型“未定义"不能用作索引类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注 WintellectNow React 和 TypeScript 教程.在第五部分排序和过滤中,作者创建了一个具有可选属性的界面,如下所示:

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;
}

有一个名为 WidgetTableCols 的枚举,如下所示:

There is an enum called WidgetTableCols as below :

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

在一个函数中,作者像这样获取 enum 的值:

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 interface it works but later the author creates another function that only sets one of the state value and typescript says not all of the state properties are set.

谁能告诉我如何解决这个问题.

Can anybody let me know how to solve this issue.

提前致谢.

推荐答案

编译器只是告诉你 this.state.sortCol 可能没有值,因为你有 strictNullChecks标志开启.

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 it's existence:

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

这将消除错误(但您随后需要处理 fName 可以为 null 的事实).

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

您也可以使用 非空断言运算符:

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

如果您确定它存在.

这篇关于类型“未定义"不能用作索引类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆