Home > Software engineering >  What is the type declaration for the array having 2 different type of elements in typescript
What is the type declaration for the array having 2 different type of elements in typescript

Time:08-12

What can be the type of declaration for

export const serverInfo = {
    "@me": {
        unread: true,
    },
    servers: [
        {
            id: 1,
            name: "Detaux",
            unread: false,
            type: "server",
            icon: "detaux.webp",
            gif: null,
        },
        // Many more ..
        {
            type: "folder",
            servers: [
                {
                    id: 5,
                    name: "freeCodeCamp",
                    unread: true,
                    type: "server",
                    icon: "freeCodeCamp.webp",
                    gif: null,
                },
                // Many more ..
            ],
        },
    ],
};

In this object, there are two different types of elements in the array, so I am confused about how to give a type declaration.

CodePudding user response:

You can implement two interfaces, Server and Folder, and a type Info using an union type (actually, Info could also be an interface):

interface Server {
  id: number;
  name: string;
  unread: boolean;
  type: string;
  icon: string;
  gif: string;
}

interface Folder {
  type: 'folder';
  servers: Server[];
}

type Info = { '@me': { unread: boolean }; servers: Array<Server | Folder> };

export const serverInfo: Info = { ... };

Edit: Works fine for me:

export const serverInfo: Info = {
  '@me': {
    unread: true
  },
  servers: [
    {
      id: 1,
      name: 'Detaux',
      unread: false,
      type: 'server',
      icon: 'detaux.webp',
      gif: null
    },
    // Many more ..
    {
      type: 'folder',
      servers: [
        {
          id: 5,
          name: 'freeCodeCamp',
          unread: true,
          type: 'server',
          icon: 'freeCodeCamp.webp',
          gif: null
        }
        // Many more ..
      ]
    }
  ]
};
  • Related