【问题标题】:The type returned from the numeric index must be a subtype of the type returned from the string index从数字索引返回的类型必须是从字符串索引返回的类型的子类型
【发布时间】:2015-11-10 22:28:44
【问题描述】:

http://www.typescriptlang.org/Handbook#interfaces-array-types 这是什么意思 “限制从数字索引返回的类型必须是从字符串索引返回的类型的子类型。”

谁能举个例子?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    仅供参考,有两种类型的索引签名,字符串和数字。

    字符串索引签名:

    [index: string]: SomeType
    

    这表示当我通过字符串索引访问此对象的属性时,该属性将具有SomeType 类型。

    数字索引签名:

    [index: number]: SomeOtherType
    

    这表示当我通过数字索引访问此对象的属性时,该属性将具有SomeOtherType 类型。

    需要明确的是,通过字符串索引访问属性是这样的:

    a["something"]
    

    按数字索引:

    a[123]
    

    您可以同时定义字符串索引签名和数字索引签名,但数字索引的类型必须与字符串索引相同,或者必须是字符串索引返回的类型的子类。

    所以,这没关系:

    interface SomeInterface {
        [index: string]: Fruit;
        [index: number]: Fruit;
    }
    

    因为两个索引签名具有相同的类型Fruit。但你也可以这样做:

    interface SomeInterface {
        [index: string]: Fruit;
        [index: number]: Apple;
    }
    

    只要AppleFruit 的子类。

    【讨论】:

      猜你喜欢
      • 2018-07-24
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      • 2021-07-29
      • 2023-02-03
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      相关资源
      最近更新 更多