推送数据时在TypeScript中键入数组

时间:2019-09-14 15:04:50

标签: javascript typescript

我在Typescript中键入一个数组,在其中推送了一些对象,但是找不到正确的方法。

这是代码:

interface IUsersItem {
  name: string;
  surname: string;
  email: string;
}

interface ISeeds {
  [key: string]: IUsersItem[];
}

const seeds: ISeeds = {
  Users: [
    {
      name: "aaa",
      surname: "bbb",
      email: "aaa.bbb@example.com"
    },
    {
      name: "ccc",
      surname: "ddd",
      email: "ccc.ddd@example.com"
    }
  ]
};

interface IModelsItem {
  name: string;
  someMethod: string;
}
interface IModels {
  [key: string]: IModelsItem;
}

const models = {
  Users: {
    name: "Users",
    someMethod: "xxx"
  }
};

let dataToSeed = [];
Object.keys(seeds).forEach((item) => {
  dataToSeed.push({
    data: seeds[item],
    model: models[item]
  });
});

这是TypeScript游乐场中的示例:http://www.typescriptlang.org/play/#code/JYOwLgpgTgZghgYwgAgJIFUDO1OsgW2QG8AoZZEOfCALmUzClAHMBuM+gVykuroaYg2HCPjjAANv0Yt2AXxIlQkWIhSoAyhAgATTMQ4BtANYQAntMHMAunQzYouAoevzFCAPYgG9bXrtauvoAvAbkWDh0hhzkpOTxFFS0yABEcOkpADQx8ZjcvMkpAEYlWTnkouJSqelwAHQlRQACEAAeVAAOEhB1nvgpOXLZCXEJiXypCFNlY1w8SXQpOsszY5WSi1MIdcs6Le34XT19AwkK5NYkcuxK4NDwSGgAsh46EBJOomHjyQKyHJgPNQnhAwAALV6Wf4KZT3NTPV7vfSjEzmKFCWwIt4fPCiNwkTzeMDIfCIj7IUKjCKOOijcgFRbUzCrciA4GgiE6RatHmnZAKa6KbrEnRwMBwAAqHkCOgpyBc7AA8kUAFYQBBgOqmMyYAAU2CCAEo6jAPFAAKKIMG63XAAiGikAPm+ovFUpldQ6nEw1rpyFdcH4fkwhjtomsw3ipOxdGjSNDBEu5DkhvkqZIQA

任何帮助都将受到欢迎!

2 个答案:

答案 0 :(得分:0)

没有为class Ticket(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) name = models.CharField(max_length=120) quantity = models.SmallIntegerField() price = models.FloatField() def __str__(self): return '{} {}'.format(self.event.name, self.name) 提供类型,因此会自动推断出缺少models的类型。

[key: string]

您可以按如下方式向{ User: { name: string; someMethod: string; }; } 添加类型。

models

答案 1 :(得分:-2)

该错误是在将其放入dataToSeed数组到期模型时发生的。为任何类型的常量提供类型。

const模型:any = {   用户:{     名称:“用户”,     someMethod:“ xxx”   } };