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

Time:02-28

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

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>
  }
}

CodePudding user response:

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.

  • Related