Estoy tratando de escribir el contenedor en window.fetch.
type MyResponse<T> = { response: Response; data: T; } type MyResponseType = 'JSON' | 'EMPTY'; async function makeRequest<T, R extends MyResponseType>(url: string, responseType: R): Promise<MyResponse<R extends 'JSON' ? T : undefined>> { const response = await fetch(url); if (responseType === 'JSON') { const data = await response.json() as T; return { response, data } // Type 'T' is not assignable to type 'R extends "JSON" ? T : undefined' } else if (responseType === 'EMPTY') { return { response, data: undefined } // Type 'undefined' is not assignable to type 'R extends "JSON" ? T : undefined' } else { return { response, data: undefined } // Type 'undefined' is not assignable to type 'R extends "JSON" ? T : undefined' } } /* Returns Promise<MyResponse<string>>, correct */ function fetchData() { return makeRequest<string, 'JSON'>('https://google.com', 'JSON') } /* Returns Promise<MyResponse<undefined>>, correct */ function fetchNoData() { return makeRequest<void, 'EMPTY'>('https://google.com', 'EMPTY') }¿Como arreglarlo?
Tal vez realmente no necesito R genérico o parámetro de tipo de responseType , pero me gustaría inferir T si paso algo que no sea nulo | indefinido, y me gustaría inferir indefinido si paso void | indefinido.
Por favor, no des consejos como "usa axios", "usa cualquiera (desconocido)". Es un pequeño fragmento de código del proyecto en el que no estoy trabajando solo, por lo que no puedo volver a escribirlo, solo escribirlo fuertemente.
Un pequeño refactor depende de usted.