打字稿对象

时间:2018-05-23 08:07:50

标签: typescript object javascript-objects

请协助,我试图将对象转换为某个实例。 我有以下数据作为API的对象:

{
"0": {
    "0": {
        "1": 2
    },
    "1": {
        "1": 5
    },
    "2": {
        "1": 9
    },
    "3": {
        "1": 3
    },
    "4": {
        "1": 1
    }
},
"1": {
    "0": {
        "1": 7
    },
    "1": {
        "1": 6
    },
    "2": {
        "1": 10
    },
    "3": {
        "1": 8
    },
    "4": {
        "1": 4
    }
  }
}

我的枚举如下:

  export enum Enum3 {
    week1 = 0,
    ....
    week4
  }


   export enum Enum2 {
        day1 = 0,
        .....
        day10
   }

   export enum Enum1 {
        monday = 0,
        .....
        friday
   }

尝试以下方式声明但不起作用:

         // number is the number of racers entering the race
        let RaceDay: {[key: Enum1 ]: number };
        let Days: {[key: Enum2 ]: RaceDay[Key] };
        let Weeks: {[key: Enum3 ]:  Days[Key] };

        Weeks = ApiData; // data above.

我如何声明或实例化这样的对象? 谢谢。

1 个答案:

答案 0 :(得分:1)

您有3次嵌套对象结构:

interface RaceDay {
  [key: string]: number
}
interface Days {
  [key: string]: RaceDay
}
interface Weeeks {
  [key: string]: Days
}

const data: Weeks = { } as Weeks; // your object with type of 'Object' as above

指定您的对象适合我。希望有所帮助。