Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TS Why I dont set an array at Promise in fetch?

I learn TS, and I have seen this code. There is a code like this:

type FetchPokemonResult<T> = T extends undefined ? Promise<PokemonResults> : void;

It retuns a array of json data. So Why is that not Promise<PokemonResults[]> ? Why is it without an array ?

code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

interface PokeArr {
  name: string;
  url: string;
}

interface PokemonResults {
  count: number;
  next: string;
  previous: null;
  results: PokeArr[];
};

type FetchPokemonResult<T> = T extends undefined ? Promise<PokemonResults> : void;

function fetchPokemon<T extends undefined | ((data: PokemonResults) => void)>(url: string, cb?: T): FetchPokemonResult<T> {
  if(cb) {
    fetch(url)
      .then(res => res.json())
      .then(cb)
    return undefined as FetchPokemonResult<T>;
  } else {
    return fetch(url).then(res => res.json()) as FetchPokemonResult<T>
  }
}

>Solution :

It’s typed this way because the function supports providing a callback cb, or returning a promise.

// typeof e is PokemonResults
fetchPokemon("", (e => console.log(e)));

// typeof e is PokemonResults
fetchPokemon("")?.then(e => console.log(e));

It retuns a array of json data. So Why is that not Promise<PokemonResults[]> ? Why is it without an array ?

It doesn’t seem to return an array. Based on your question it returns a PokemonResults which has a list results.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading