Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

184
Vistas
Type assertion for promises with multiple return types

I've been having trouble using type assertions with multiple promise return types. Here's a stripped down version of the code:

interface SimpleResponseType {
   key1: string
};

interface SimpleResponseType2 {
   property1: string
   property2: number 
};

interface ServiceType {
   fetchResponse: () => Promise<SimpleResponseType | SimpleResponseType2> 
};

class Service implements ServiceType {
   async fetchResponse() {
      // code to fetch some api data and return some json
      // just return a pretend/sample response 
      return { key1: 'json' };
   };
};

const service = new Service();

await service.fetchResponse().then(resp => {
   // Should be typeof SimpleResponseType
   console.log(resp.key1)
})

TypeScript will underline the last key1 and throw this error:

Property 'key1' does not exist on type 'SimpleResponseType2'.ts(2339)

Which makes sense, but when I attempt to assert the type more errors show up. For example asserting it like this:

await service.fetchResponse().then((resp as SimpleResponseType) => {

It throws this err:

Argument of type 'SimpleResponseType' is not assignable to parameter of type '(value: SimpleResponseType | SimpleResponseType2) => SimpleResponseType | SimpleResponseType2 | PromiseLike<...>'.
Type 'SimpleResponseType' provides no match for the signature '(value: SimpleResponseType | SimpleResponseType2): SimpleResponseType | SimpleResponseType2

The only assertion I can get working is like this:

const respTyped = resp as SimpleResponseType

And then use respTyped instead of resp.

Maybe there's a better way to accomplish this?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You could potentially use overloads. But you would need to have different input parameters on the function. I don't know your specific case but it seems a bit odd that there could be two different return types for the same exact API/function call.

Edit: You can try something like this, if you want to use the same function for multiple API routes.

TS playground

interface SimpleResponseType {
   key1: string
};
interface SimpleResponseType2 {
   property1: string
   property2: number 
};
type SimpleResponseType3 = Array<SimpleResponseType2>;

enum Routes {
    Route1 = "/api/route1",
    Route2 = "/api/route2",
    RouteWParam = "/api/route2/:id"
}

class Service {

    async fetchResponse(route: Routes.Route1) : Promise<SimpleResponseType>;
    async fetchResponse(route: Routes.Route2) : Promise<SimpleResponseType2>;
    async fetchResponse(route: Routes.RouteWParam, params: { id: number }) : Promise<SimpleResponseType3>;
    async fetchResponse(route: Routes, params?: Record<string, string | number>) {
        let url : string = route;
        if (params !== undefined) {
            //replace all params with the params passed
            url = Object.entries(params).reduce((previousValue: string, [param, value]) => {
                return previousValue.replace(`:${param}`, '' + value)
            }, route);
        }
        // You do lose type-safety inside this function. TS doesn't care if route is `Route1` and you try to return `SimpleResponseType2`.
        // That's up to you to make sure.
        const data = { key1: 'sdf' }
        const data2 = { property1: 'val', property2: 345 };
        
        return new Promise((res) => {
            setTimeout(() => res(data2), 100)
        })
    };
};
about 4 years ago · Juan Pablo Isaza Denunciar

0

It's not entirely clear what you're aiming to achieve but perhaps this is what you're aiming for. Strongly typing your Service type so that you know the precise response type.

interface SimpleResponseType {
   key1: string
};

interface SimpleResponseType2 {
   property1: string
   property2: number 
};

interface ServiceType<T extends SimpleResponseType | SimpleResponseType2> {
   fetchResponse: () => Promise<T> 
};

class Service implements ServiceType<SimpleResponseType> {
   async fetchResponse() {
      // code to fetch some api data and return some json
      // just return a pretend/sample response 
      return { key1: 'json' };
   };
};

const service = new Service();
export {}
await service.fetchResponse().then(resp => {
   // Should be typeof SimpleResponseType
   console.log(resp.key1)
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

return { key1 = 'json' };

It looks like you are doing something strange. What if you type:

return { key1: 'json' };
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda