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

395
Visualizações
How to return Generic Type in arrow function React-TypeScript

I just trying to make one custom hook in react. everything works fine but now I want to add the return type of my response for that I have made my hook function to typescript generic arrow function. Now when I try to return this generic type from my hooks I'm getting an error inside my hooks.

Type '{ name: string; }' is not assignable to type 'T'. 'T' could be instantiated with an arbitrary type which could be unrelated to '{ name: string; }'.

hooks

type httpRequest = {
  URL: string | undefined;
  Method: 'Get' | 'Post' | 'Put' | 'Delete';
  RequestBody: any;
};

type httpResponse<T> = {
  loading: boolean;
  data: T;
  error: any;
};

const useHttpRequest = <T>(request: httpRequest): httpResponse<T> => {
  console.log();

  return { loading: false, data: { name: 'Sabban' }, error: {} };
};

export default useHttpRequest;


Component

import React from 'react';
import useHttpRequest from '../hooks/use-http';

const Blog = () => {
  const httpRequest = useHttpRequest<{ name: string }>({
    URL: '',
    Method: 'Get',
    RequestBody: {},
  });

  return (
    <div className="container">
      <div className="card">
        <div className="card-body">
          <h5 className="card-title">Card title</h5>
          <h6 className="card-subtitle mb-2 text-muted">Card subtitle</h6>
          <p className="card-text">
            Some quick example text to build on the card title and make up the
            bulk of the card's content.
          </p>
        </div>
      </div>
    </div>
  );
};

export default Blog;

I just want to return the exact type that I'm getting from the component.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It is because the type system cannot ensure what will be substituted to T within the phrase of declaring.

In your example, data is retuning as { name: 'Sabban' } which is not safe because the function can be called like useHttpRequest<{ fullname: string }>.

It seems that you are building a Http client, I think it is fine to force cast { name: 'Sabban' } as unknown as T because it is impossible to ensure what will be got from external response.

Or, if you are able to list out all apis and all response types, you can define a method for each endpoints. Which is like building a SDK client. Example: playground

about 4 years ago · Juan Pablo Isaza Relatório
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