Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

112
Visualizações
Generic fetch wrapper

I am trying to write the wrapper under 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')
}

How to fix it?

Maybe I don't really need generic R or responseType param, but I would like to infer T if I pass anything that is not void | undefined, and I would like to infer undefined if I pass void | undefined.

Please don't give advice like "use axios", "use any (unknown)". It is a small piece of code from the project where I am not working single so I am not able to rewrite it, just to strongly type it.

A small refactor is up to you.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda