Виктория
Виктория

Reputation: 168

how to make typing two objects in an array or the whole array?

I did the typing using TypeScript, it works correctly for one object. But when I create two objects I get an error. how to make this code work correctly? maybe that's not how I write typing?

export type TestType = [
  {
    id: string;
    fullname: string;
    appId: string;
    status: StatusValue[];
  },
];

export type StatusValue = {
  text: string;
  background: string;
};

2

import { TestType } from './types';

class Testpage {
  data: TestType = [
    {
      id: '1423',
      fullname: 'Hello world',
      appId: '32112324dsadas123123',
      status: [
        {
          text: 'test',
          background: '#fff',
        },
      ],
    },
    {
      id: '1422',
      fullname: 'Hello world2',
      appId: '32112324dsadas1231233',
      status: [
        {
          text: 'test2',
          background: '#000',
        },
      ],
    },
  ];
}

export default Testpage;

Upvotes: 0

Views: 46

Answers (1)

Irfanullah Jan
Irfanullah Jan

Reputation: 3902

This is because you have hardcoded TestType to an array with a single object. Instead of this way change TestType to look like the following:

export type TestType = {
    id: string;
    fullname: string;
    appId: string;
    status: StatusValue[];
};

Now use it like:

class Testpage {
  data: TestType[] = [
    {
      id: '1423',
      fullname: 'Hello world',
      appId: '32112324dsadas123123',
      status: [
        {
          text: 'test',
          background: '#fff',
        },
      ],
    },
    {
      id: '1422',
      fullname: 'Hello world2',
      appId: '32112324dsadas1231233',
      status: [
        {
          text: 'test2',
          background: '#000',
        },
      ],
    },
  ];
}

Upvotes: 2

Related Questions