【问题标题】:TypeScript Interface Array Type error TS2411TypeScript 接口数组类型错误 TS2411
【发布时间】:2016-02-22 10:31:56
【问题描述】:

我很难理解这一点:

支持的索引类型有两种:字符串和数字。可以同时支持这两种类型的索引,但限制是从数字索引返回的类型必须是从字符串索引返回的类型的子类型。

虽然索引签名是描述数组和“字典”模式的有效方式,但它们还强制所有属性都匹配其返回类型。在这个例子中,属性与更通用的索引不匹配,类型检查器给出错误:

interface Dictionary {
    [index: string]: string;
    length: number;    // error, the type of 'length' is not a subtype of the indexer
}

来源:TypeScript Handbook's interface

我已经尝试了 4 个案例,但仍然无法理解发生了什么。谁能解释为什么只有[index: string]: string; 会有错误TS2411?

另一种情况:

【问题讨论】:

  • 你错过了一个codio@compact-guide。反正我看不出有什么隐藏它的理由
  • 正好错过了两个.....
  • 不错。隐藏它让我想了解更多:)

标签: typescript


【解决方案1】:

TypeScript 2.4 的解决方法是

interface Dictionary {
    [index: string]: string | number;
    length: number;
}

但是,您可能需要在使用时显式转换

let v = dict.key as string

【讨论】:

    【解决方案2】:

    可以同时支持这两种类型的索引,但限制是从数字索引返回的类型必须是从字符串索引返回的类型的子类型。

    也没有问号,答案是否定的。这个数组不会以任何方式工作:

    interface Dictionary {
        [index: string]: string;
        length: number;  // error
    }
    

    因为即使这样也行:

    interface Dictionary {
        [index: string]: string;
    }
    
    var dic: Dictionary = {}
    dic[1] = "123"
    

    请注意,我们使用数字索引字符串数组。

    interface Dictionary { [index: string]: MYCLASS; } 是为了支持你定义允许的值,而不是索引的类型,对不起

    你做的不是接口而是数组:http://www.typescriptlang.org/Handbook#interfaces-array-types

    【讨论】:

      【解决方案3】:

      如果您有[index: string]: string; 所有属性都必须是string。因此:

      interface Dictionary {
          [index: string]: string;
          length: number;    // error, length is not a string.
      }
      

      【讨论】:

      • 谢谢,很抱歉回复晚了。我太傻了。我在你的答案中再包含一个测试用例,你能帮帮我吗?
      • 抱歉,我不清楚您对哪个代码示例有疑问
      • 对不起,我只是添加它。
      • 如果您在操场上尝试,这种情况也是错误的。我想你有一个旧版本的 tsc
      • 只有再添加一行才会出错 -->var foo:Dictionary=['peter','john'];
      猜你喜欢
      • 2019-04-27
      • 2019-07-07
      • 2019-01-09
      • 2018-09-15
      • 2012-11-04
      • 2022-09-28
      • 2021-06-04
      • 2020-06-16
      • 2021-08-07
      相关资源
      最近更新 更多