Doubt about creating event maps - Typescript

Asked

Viewed 52 times

0

I am an intern and I took on a project in a language that I don’t know much about, I’m having problems creating a return of events, I tried to look for similar errors on the internet, but without success. Follow the error:

[![Image showing where the error occurs][1]][1]

And the code:

return api.post<Response, apiEvent[]>('execute', data).then(() => {
  const events: IEvent[] = response.map((item: apiEvent): IEvent[] => {
    // ...
  });
});

Another mistake that gives in events is:

Type 'IEvent[][]' is not assignable to type 'IEvent[]'.

If any of you could try to explain to me the reason for the mistake, I would appreciate it very much.

1 answer

1

The callback of map does not return an array of IEvent, but rather a IEvent.

Change the return note from callback of IEvent[] for IEvent. The array type IEvent[] is returned by whole the map, so that each callback only returns one event.


But by correcting the above error, another error will arise:

Function Lacks ending Return statement and Return type does not include 'undefined'.

This is because, when you set an explicit function return annotation, Typescript will check that all code paths will return the type you explicitly specified.

Think of this example:

function sum(a: number, b: number | undefined): number {
  if (b) {
    return a + b;
  }

  // O TypeScript irá reclamar, uma vez que, se `b` não estiver
  // definido, este caminho não retornará nada (no caso, um número
  // não será retornado). Desse modo, como anotamos explicitamente
  // o retorno da função como `number`, o erro ocorre.
}

To correct the error then, you must ensure that all paths return the type specified by you.

  • i did as you said, but the error I showed in the image persisted. The code looks like this: return api.post<Response, apiEvent[]>('execute', data).then(() => { const events: IEvent[] = response.map((item: apiEvent): IEvent => { // ... }); });

  • Strange... I could then try to reproduce the even problem in the Typescript playground and paste the link into your question, please? cc: @Jonatan

  • Done, @Luizfelipe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.