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