无法将类型“字符串”分配给类型“” GET”

时间:2020-05-07 15:07:47

标签: typescript axios typescript-typings

我有一个使用axios库执行某些请求的自定义钩子:

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


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

{...}
}

我带来了将method声明为Method类型的Axios类型(AxiosRequestConfig):

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

不幸的是,method突出显示了以下错误: Type 'string' is not assignable to type '"GET" | "get" | "delete" | "DELETE" | "head" | "HEAD" | "options" | "OPTIONS" | "post" | "POST" | "put" | "PUT" | "patch" | "PATCH" | undefined'.

code error

我始终可以将method键入为string,但这会破坏我正在寻找的类型安全性。

2 个答案:

答案 0 :(得分:2)

我始终可以将method键入为string,但这会破坏我正在寻找的类型安全性。

method应该是Method中的axios类型,而不是string

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

由于它们都具有默认值,因此您可能还需要默认整体参数:

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

On the playground

答案 1 :(得分:0)

我必须声明一个类型为 Method 的变量方法并将其包含在请求中。

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

... 只是与问题无关的其他变量。