【问题标题】:Error TS2322: Type 'Object[]' is not assignable to type '[Object]'错误 TS2322:类型“Object[]”不可分配给类型“[Object]”
【发布时间】:2017-04-10 00:25:02
【问题描述】:

我有一个这样的代码 sn-p:

export class TagCloud {

    tags: [Tag];
    locations: [Location];

    constructor() {
        this.tags = new Array<Tag>();
        this.locations = new Array<Location>();
    }
}

但这给了我以下错误:

错误 TS2322:类型“Tag[]”不可分配给类型“[Tag]”。 “Tag[]”类型中缺少属性“0”。

错误 TS2322:类型 'Location[]' 不可分配给类型 '[Lo 阳离子]'。 “Location[]”类型中缺少属性“0”。

我做错了什么(代码可以运行)?

我正在使用带有 es6-shim 类型描述 (https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/es6-shim) 的类型。

【问题讨论】:

    标签: typescript ecmascript-6 typescript-typings definitelytyped


    【解决方案1】:

    在 typescript 中,当你声明一个数组时,你可以这样做:

    let a: Array<number>;
    

    let a: number[];
    

    使用时:

    let a: [number];
    

    您实际上是在声明 a tuple,在这种情况下,长度为 1 和数字。
    这是另一个元组:

    let a: [number, string, string];
    

    你得到这个错误的原因是因为你分配给tagslocations的数组长度是0,应该是1。

    【讨论】:

      【解决方案2】:

      您想使用 Tag[] 告诉 TypeScript 您正在声明一个 Tag 数组。

      export class TagCloud {
      
          tags: Tag[];
          locations: Location[];
      
          constructor() {
              // TS already knows the type
              this.tags = []
              this.locations =[]
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2023-01-25
        • 2019-02-07
        • 1970-01-01
        • 1970-01-01
        • 2020-11-23
        • 2021-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多