我有一个使用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'.
我始终可以将method
键入为string
,但这会破坏我正在寻找的类型安全性。
答案 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 = {}) => {
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^
答案 1 :(得分:0)
我必须声明一个类型为 Method 的变量方法并将其包含在请求中。
let method: Method = 'POST';
const request = {
...
method: method
...
}
... 只是与问题无关的其他变量。