Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
¿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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!