typescript - 使用正文在 post 请求上指定 Axios 响应类型
问题描述
我正在尝试同时指定 JSON 正文和响应类型(它们是不同的,那里的一些样本不知何故两者都相同)。
错误信息:
'{ grant_type: string; 类型的参数 refresh_token:字符串;}' 不可分配给“AuthResponse”类型的参数。
对象字面量只能指定已知属性,并且“AuthResponse”类型中不存在“grant_type”。
这是我定义为我的类型的响应:
export interface AuthResponse {
token: string;
token_type: string;
access_token: string;
access_token_expires_at: string;
refresh_token: string;
refresh_token_expires_at: string;
}
axios的使用:
axios
.post<AuthResponse>(
secrets.authURL,//Defined in enclosing class
{
grant_type: this.grantType,//Defined in enclosing class
refresh_token: this.authPayload,//Defined in enclosing class
},//<-- Defined as data and conflicts with AuthResponse
{
headers: {
Authorization: this.getAuthHeader(),//Defined in enclosing class
"Content-Type": this.contentType,///Defined in enclosing class
},
}
)
.then((axiosResp) => {
const response = axiosResp.data;//<-- Not the type I'd expect
});
axiosResp.data
是 type{grant_type: ..., refresh_token: ...}
而不是AuthResponse
.
从普通的 JS 示例中,数据是请求的主体,但不知道为什么它会被强制与响应相同,所以我一定做错了什么。
编辑/回答: 正如@jrsharpe 的评论所指出的,这是一个错误,他们几个小时前也刚刚发布了v0.23.0 。它修复了错误 #4116。所以只需升级到 0.23.0+。
解决方案
你可以像这样输入
interface AuthResponse {
token: string;
token_type: string;
access_token: string;
access_token_expires_at: string;
refresh_token: string;
refresh_token_expires_at: string;
}
interface TBody {
grant_type: string
refresh_token: string
}
const t = async (): Promise<void> => {
const data = await axios.post<AuthResponse, AxiosResponse<AuthResponse, TBody>, TBody>("theurl", {
grant_type: 'kjkjk',
refresh_token: "dddf",
}, {
headers: {
Authorization: "dfdfds",
"Content-Type": "application/json",
},
})
const resu: AuthResponse = data.data
}
推荐阅读
- github - /github/home 是否在 github 操作之间持续存在?
- java - 使用 Java-ee-7.0 for IBM 从 Jax-rs 1.1 迁移到 2.0 的问题是 9
- c# - 如何冒泡异常
- c# - 为什么在接口上调用方法使用基本实现而不是覆盖?
- java - 补丁与合并补丁哪个合适?
- angular - 如何在 Angular 项目的生产版本中禁用缩小和丑化/混淆?
- c++ - 即使初始要求为真,也不会进入 for 循环
- asp.net-core - 如何使用 IdentityServer4 验证 x509 签名凭据
- firebase - Firebase - 升级到 6.9.0 后无法提供本地功能
- javascript - 用于文本的 Google Script IF 语句