Home > Software design >  Typescript - Not all code paths return a value
Typescript - Not all code paths return a value

Time:04-13

I'm currently working on a Firebase Cloud Function with Node and Typescript.

As one of the steps I call the PokeAPI through a client and if there is a response, It returns the data with a specific format. Otherwise, throws an Error to be catch by the parent function and send a response to the client with that Error.

But Typescript warns me that "Not all code paths return a value" in my function, true, only If the call succeeds will data be returned. I've tried to type the function return but still warns me about it. May I refactor the function to always return a value or just ignore Typescripts message?

Functional that I'm talking about:

import {PokemonClient} from "pokenode-ts";

export const searchPokemonWithPokeApi = async (pokemonName: string) => {
  try {
    const client = new PokemonClient({
      cacheOptions: {maxAge: 10000, exclude: {query: false}},
    });
    const response = await client.getPokemonByName(pokemonName);
    const searchResult = {
      id: response.id,
      name: response.name,
      height: response.height,
      weight: response.weight,
      abilities: response.abilities.map((ability) => ability.ability.name),
      stats: response.stats.map((stat) => ({
        name: stat.stat.name,
        base_stat: stat.base_stat,
      })),
      types: response.types.map((type) => type.type.name),
      sprite: response.sprites.front_default,
    };
    return searchResult;
  } catch (error) {
    if (!(error instanceof Error)) throw new Error("Something went wrong");
    if (error.message === "Request failed with status code 404") throw new Error("Pokemon not found");
  }
};


CodePudding user response:

The problem is that in the catch clause, if none of the two if conditions are fulfilled, no value is returned (or thrown).

I guess you forgot to add throw error at the end to rethrow the error if it's something other than a 404:

try {
  /* ... */
} catch (error) {
  if (!(error instanceof Error)) throw new Error("Something went wrong");
  if (error.message === "Request failed with status code 404") throw new Error("Pokemon not found");
  throw error;
}
  • Related