How to return Generic Type in arrow function React-TypeScript

Viewed 531

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.

1 Answers

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

Related