Home > Software engineering >  Typescript - how to get interface handle single or multiple objects
Typescript - how to get interface handle single or multiple objects

Time:04-28

I have a question in regards to extending an interface to allow duplicate fields. Basically I need to create 2 requests. One request handles one event, the other request handles 2 events.

Example:

One event request:

events[
{
  "name": "EventOne"
  "description": EventOne Description
}
]

Two events request:

events[
{
  "name": "EventOne"
  "description": EventOne Description
},
{
  "name": "EventTwo"
  "description": EventTwo Description
}
]

So I have a method then sends a request like so:

export function performRequest(params: IEvent) {
  return request(test)
    .post(`/events`)
    .send(params);

I then have two interfaces. One deals with a single request object (IEventDetails), the other extends the IEventDetails and handles the two events request which is known as IMultiEventDetails:

interface IEvent {
  events: [IEventDetails];
}

interface IEventDetails {
name?: string;
description?: string;
}

interface IMultiEventDetails extends IEventDetails{
name?: string;
description?: string;
}

Now when I call on my requests, it works for the single event, but not for the multi event as it gives me the error:

Source has 2 element(s) but target allows only 1

When I call my requests:

Below works:

const response = await performRequest({
events[{
      name: "EventOne"
      description: "EventOne Description"
}]
...

Below errors:

    const response = await performRequest({
    events[{
          name: "EventOne"
          description: EventOne Description
    },
    {
          name: "EventTwo"
          description: EventTwo Description
    }]
    ...

This makes sense as I am not calling on the IMultiEventDetails. I am trying to avoid creating one method to call on single event and another method to call on multi event. So it there a way in order to call on IEvent and have it to be able to handle single or multi event requests?

CodePudding user response:

[IEventDetails] specifies an array with one element

IEventDetails[] specifies an array of IEventDetails type, so any number of IEventDetails is fine

interface IEvent {
  events: IEventDetails[];
}

interface IEventDetails {
  name?: string;
  description?: string;
}
  • Related