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

142
Vistas
¿Hay alguna manera de usar ReturnType dentro de una función y hacer referencia a la función sin usar su nombre?

En pocas palabras, sé que puedo hacer esto:

 function my_function() : Error { return some_generic_function<ReturnType<typeof my_function>>(); }

Pero, ¿hay alguna manera de usar algo como this palabra clave para referirse a la función que contiene la llamada, pero sin usar su nombre? Me gusta:

 function my_function() : Error { //This does not work, ofc return some_generic_function<ReturnType<typeof this>>(); }

Más contexto :

Tengo varias funciones similares a un servicio que devuelven una Promesa con el mismo patrón de resolve / reject . Por lo tanto, hice una función genérica y quiero poder usarla en cada una de mis funciones similares a servicios.

 function my_generic_return<T> (data?:T, error?: Error): Promise<T> { return new Promise((resolve, reject) => { if (typeof data !== 'undefined') { return resolve(data); } return reject(); }); } function service1() : Promise<type1> { const data : type1 | undefined ... // ... // But this line is kinda ugly return my_generic_return<ReturnType<typeof service1>>() } function service2() : Promise<type2> { const data : type2 | undefined ... // ... // But this line is kinda ugly return my_generic_return<ReturnType<typeof service2>>() }

Una forma en que me gustaría modificar ese retorno es tener algo genérico en lugar del nombre de la función dentro de ReturnType<typeof function_name>

Solución:

La respuesta de @captain-yossarian es genial. Dejo que TypeScript infiera mis tipos. Aquí está mi código:

 function my_generic_return<T>(data?: NonNullable<T>, error?: Error) : Promise<NonNullable<T>> { // I use NonNullable since I never return a Promise with an undefined object. return new Promise((resolve, reject) => { if (typeof data !== 'undefined') { return resolve(data); } if (error instanceof Error) { return reject(error) } return reject(new Error("Unknown error"); }); } function service1() { const data : type1 | undefined = undefined // We may set data here... return my_generic_return(data) } function service2() { const data : type2 | undefined = undefined // We may set data here... return my_generic_return(data) } const global_data: type2 = new type2(); service2.then( // Param correctly seen as 'type2' // This is why I used NonNullable in the generic // Otherwise it would be seens as 'type2 | undefined' // because that's the type of data inside service2 (data) => { global_data = data } );
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Técnicamente es posible. some_generic_function debería esperar un parámetro genérico.

 const foo = <T,>() => null as any function my_function(): Error { return foo<ReturnType<typeof my_function>>(); }

Pero no estoy seguro de si es un buen camino a seguir.

Está pasando un parámetro genérico explícito a foo dentro de my_function pero no lo usa en absoluto. Será mejor si compartes un poco más de contexto.

ACTUALIZAR

Regla general: en el 80% no debe usar genéricos explícitos cuando llama a una función. TS debería ser capaz de inferirlo.

Considere el siguiente ejemplo:

 function my_generic_return<T>(data?: T, error?: Error): Promise<T> { return new Promise((resolve, reject) => { if (typeof data !== 'undefined') { return resolve(data); } return reject(); }); } type Foo = { tag: 'foo' } function service1<T>(data: T) { return my_generic_return(data) } // return type is Promise<Foo> function service2() { const data: Foo = null as any return my_generic_return(data) }
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