错误TS2322:类型'对象[]'不能分配给'[Object]'类型

时间:2016-11-25 15:00:51

标签: typescript ecmascript-6 typescript-typings definitelytyped

我有一个这样的代码段:

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   阳离子]'。     “位置[]”类型中缺少属性“0”。

我做错了什么(代码正在运行)?

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

2 个答案:

答案 0 :(得分:11)

在声明数组时,在typecript中,你可以这样做:

let a: Array<number>;

let a: number[];

使用时:

let a: [number];

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

let a: [number, string, string];

您收到此错误的原因是您分配给tagslocations的数组的长度为0,它应为1.

答案 1 :(得分:0)

您希望使用Tag[]告诉TypeScript您声明的数组为Tag

export class TagCloud {

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

    constructor() {
        // TS already knows the type
        this.tags = []
        this.locations =[]
    }
}
相关问题