Type 'string' is not assignable to type '"GET" | "get" | …'

Viewed 3676

I've got a custom hook that uses the axios library to perform some requests:

const useCustomHook = ({ endPoint = "", method = "GET", options = {} }) => {
  const [data, setData] = useState([]);


  const [request, setRequest] = useState<AxiosRequestConfig>({
    url: endPoint,
    method,
    headers: {},
    data: options
  });

{...}
}

I bring the Axios types (AxiosRequestConfig) that declare method to be of type Method:

type Method =
  | 'get' | 'GET'
  | 'delete' | 'DELETE'
  | 'head' | 'HEAD'
  | 'options' | 'OPTIONS'
  | 'post' | 'POST'
  | 'put' | 'PUT'
  | 'patch' | 'PATCH'

Unfortunately, method highlights the below error: Type 'string' is not assignable to type '"GET" | "get" | "delete" | "DELETE" | "head" | "HEAD" | "options" | "OPTIONS" | "post" | "POST" | "put" | "PUT" | "patch" | "PATCH" | undefined'.

code error

I can always type method as string but that would break the type safety I'm looking for.

3 Answers

I had to declare a variable method with type Method and included that in the request.

let method: Method = 'POST';
const request = {
     ...
     method: method
     ...
}

The ... is just other unrelated variables to the question.

I can always type method as string but that would break the type safety I'm looking for.

method should be of type Method from axios, not string:

interface CustomHookParam {
    endPoint?: string;
    method?:   Method; // <=== type is `Method` from `axios`'s types
    options?:  SomeAppropriateTypeForTheOptions;
}
const useCustomHook = ({ endPoint = "", method = "GET", options = {} }: CustomHookParam) => {

Since they all have defaults, you may want to default the overall parameter as well:

const useCustomHook = ({ endPoint = "", method = "GET", options = {} }: CustomHookParam = {}) => {
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^

On the playground

We can also take an advantage of enum here.

enum RequestMethods {
  GET='GET',
  POST='POST',
  PUT='PUT',
  DELETE='DELETE',
}

interface IRequestConfig {
  ...
  method: RequestMethods.GET | RequestMethods.POST | RequestMethods.PUT | RequestMethods.DELETE,
  ...
}

const request: IRequestConfig = {
  ...
  method: RequestMethods.GET,
  ...
}
Related