问题描述:

I'm trying to make dictionary/hashmap in TypeScript, and read this

However, when trying to do it like the example, I get some errors ' = expected ' and 'Invalid left-hand expression ', both in the line with 'axis["vertical"] = 4;

The line with x: number = axis["vertical"]; does not complain however. Is there something about using it inside a class I've misunderstood, or am I overlooking something?

This is my code:

var axis: { [id: string]: number; } = {"vertical": 0, "horizontal": 0};

export class Input {

x: number = axis["vertical"];

axis["vertical"] = 4;

}

I've also tried this, with exactly the same result.

var axis: axisMap = {"vertical": 4};

export class Input {

x: number = axis["vertical"];

axis["vertical"] = 4;

}

interface axisMap {

[id: string]: number;

}

网友答案:

You can't have arbitrary statements in a class body. You can do something like this:

var axis: { [id: string]: number; } = {"vertical": 0, "horizontal": 0};

export class Input {
    x: number = axis["vertical"];
    constructor() {
        axis["vertical"] = 4;
    }
}
相关阅读:
Top