类型 'string' 不可分配给类型 '"GET" | “得到” | ……”

Posted

技术标签:

【中文标题】类型 \'string\' 不可分配给类型 \'"GET" | “得到” | ……”【英文标题】:Type 'string' is not assignable to type '"GET" | "get" | …'类型 'string' 不可分配给类型 '"GET" | “得到” | ……” 【发布时间】:2020-08-22 22:47:26 【问题描述】:

我有一个自定义钩子,它使用axios 库来执行一些请求:

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


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

...

我将声明 method 的 Axios 类型 (AxiosRequestConfig) 设为 Method 类型:

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'.

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

【问题讨论】:

【参考方案1】:

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

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

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

【讨论】:

【参考方案2】:

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

method 应该是来自axiosMethod 类型,而不是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

【讨论】:

【参考方案3】:

我们也可以在这里利用枚举。

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,
  ...

【讨论】:

以上是关于类型 'string' 不可分配给类型 '"GET" | “得到” | ……”的主要内容,如果未能解决你的问题,请参考以下文章

类型 'string' 不可分配给类型 '"GET" | “得到” | ……”

构建:'string | 类型的参数1' 不可分配给“字符串”类型的参数

构建:'string | 类型的参数1' 不可分配给“字符串”类型的参数

打字稿,JSON.parse 错误:“类型 'null' 不可分配给类型 'string'。”

JWT:'string | 类型的参数undefined' 不可分配给'Secret' 类型的参数

键入'字符串 | ArrayBuffer' 不可分配给类型 'string'