【问题标题】:Typescript Objects打字稿对象
【发布时间】:2018-05-23 08:07:50
【问题描述】:

请协助,我正在尝试将一个对象转换为某物的实例。 我有以下数据作为来自 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.

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

【问题讨论】:

  • 更多代码会有所帮助。例如枚举声明
  • 从 API 获取 JSON 的代码是什么?您可能没有反序列化您的 JSON。可能缺少对JSON.parse() 的呼叫。
  • 嗨,我已经编辑了上面的问题。

标签: typescript object javascript-objects


【解决方案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

分配您的对象对我有用。希望这会有所帮助。

【讨论】:

  • 我收到以下错误Type 'Object' is not assignable to type 'Weeks'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
  • 您使用的是 Angular httpclient 还是类似的?也许试试const data: Weeks = {} as Weeks。如果您从 Angular 使用 httpClient 之类的东西,您可以使用 this.http.get<Weeks>(url);
  • 如果您的数据是“对象”类型,那么最后的as Weeks 应该可以工作。测试过了。
猜你喜欢
  • 2023-03-07
  • 2017-06-12
  • 2017-02-18
  • 2015-03-24
  • 2020-08-09
  • 2021-01-26
  • 2017-03-22
  • 1970-01-01
相关资源
最近更新 更多