【问题标题】:Type 'undefined' cannot be used as index type类型“未定义”不能用作索引类型
【发布时间】:2017-10-05 18:50:05
【问题描述】:

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

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

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

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

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

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

我在这里得到类型 undefined 不能用作索引类型。如果我从界面中删除 ? 它可以工作,但后来作者创建了另一个只设置一个状态值的函数,TypeScript 说并非所有状态属性都已设置。

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

【问题讨论】:

  • 你在用strictNullChecks吗?
  • 是的,strictNullChecks 为真。我把它改成了假的。现在它的工作。

标签: javascript reactjs typescript


【解决方案1】:

编译器只是告诉您this.state.sortCol 可能没有值,因为您打开了strictNullChecks 标志。

你可以先检查它是否存在:

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

这将消除错误(但您需要处理fName 可以为空的事实)。

您也可以使用Non-null assertion operator:

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

如果你确定它存在的话。

【讨论】:

  • 感谢您的解释。将与非空断言运算符一起使用。
  • Javascript 允许将 undefined 用作索引类型。所以以下工作: x = {}; x[未定义] = 3;为什么打字稿不允许呢?
  • @Aaron in js 对象的键是 always 字符串,当你这样做x[undefined] = 3; 时,你基本上得到了这个x["undefined"] = 3;。 Typescript 只是强迫你承认这一点。
  • 即使事先进行了严格的检查,为什么还会出现这种情况?即if (this.state.sortCol && !!this.state.sortCol && etc..) WidgetTableCols[this.state.sortcol] ?
【解决方案2】:

有两件事可以解决这个烦人的问题:

  1. tsconfig.json 文件中将strictNullChecks 标志设置为false

    {
      "compilerOptions": {
        "strictNullChecks": false,
        "baseUrl": "./src",
        ~ ~ ~
    
  2. 使用optional chaining 获得安全代码并避免崩溃:

                         //     ↙ add undefined type because it's possible
    const fName: string | undefined =  //     ↙ use "?" operator to be safe
          WidgetTableCols[this.state.sortCol]?.toLocaleLowerCase();
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2018-02-13
    • 2023-01-31
    • 1970-01-01
    • 2021-12-16
    • 2021-05-14
    相关资源
    最近更新 更多