【发布时间】:2019-11-27 12:27:23
【问题描述】:
我是 TypeScript 的新手,所以我边走边学。我想创建一个 axios 实例以在我的代码中重用,我只需要在需要的地方传递道具。我正在使用 React。
// in a utils folder
// axios.ts
import axios from 'axios'
type Method =
| 'get' | 'GET'
| 'delete' | 'DELETE'
| 'head' | 'HEAD'
| 'options' | 'OPTIONS'
| 'post' | 'POST'
| 'put' | 'PUT'
| 'patch' | 'PATCH'
| 'link' | 'LINK'
| 'unlink' | 'UNLINK'
interface AxiosProps {
/** Web URL */
url: string,
/**
* POST method: GET, POST, PUT, DELETE
* @default GET
*/
method?: Method,
/** Header options */
header?: object,
/** Optional Data for POST */
data?: object,
/** Optional params */
params?: object
}
export function Axios(props: AxiosProps) {
/**
* Creates an axios instance.
*
* @see https://github.com/axios/axios
* @return Promise
*/
const instance = axios.create({
baseURL: process.env.REACT_APP_API_ENDPOINT,
headers: { 'Content-Type': 'application/json' },
url: props.url, // must have a starting backslash: /foo
params: props.params,
data: props.data,
withCredentials: true,
})
return instance
}
我从axios 得到Method 类型。
现在,使用实例:
import {Axios} from '../utilities/axios'
// I'd like to achieve this in an async function:
const {data} = await Axios({url: '/foo' /**, method: 'POST' **/})
console.log(data)
以上,TS抱怨:
'await' 对这个表达式的类型没有影响
请问如何实现这个逻辑?我知道我需要学习更多的打字稿,但在我学习的时候我会“挨打”。谢谢
【问题讨论】:
标签: javascript reactjs typescript axios