【问题标题】:Crating a type of array of multiple objects创建一种类型的多个对象的数组
【发布时间】:2022-06-15 04:52:04
【问题描述】:

我想为对象数组创建一个类型。对象数组可能如下所示:

   const troll = [
      {
        a: 'something',
        b: 'something else'
      },
      {
        a: 'something',
        b: 'something else'
      }
    ];

我尝试使用的类型是:

export type trollType = [{ [key: string]: string }];

然后我想使用这样的类型:

   const troll: trollType = [
      {
        a: 'something',
        b: 'something else'
      },
      {
        a: 'something',
        b: 'something else'
      }
    ];

但我收到此错误:

Type '[{ a: string; b: string; }, { a: string; b: string; }]' is not assignable to type 'trollType'.
  Source has 2 element(s) but target allows only 1

我可以这样做:

export type trollType = [{ [key: string]: string }, { [key: string]: string }];

但是假设我的对象数组将有 100 个对象。

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    在为数组设置类型时,它应该采用这种格式any[]

    所以你的情况

    export type trollType = { [key: string]: string }[];
    

    【讨论】:

      【解决方案2】:

      您可以尝试使用Record 类型来存储对象属性定义并从中创建一个数组,如下所示:

      type TrollType = Record<string, string>[];
      
      const troll: TrollType = [
            {
              a: 'something',
              b: 'something else'
            },
            {
              a: 'something',
              b: 'something else'
            }
          ];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-01
        • 2011-09-29
        相关资源
        最近更新 更多