gpt4 book ai didi

javascript - 更改有效载荷的类型

转载 作者:行者123 更新时间:2023-11-30 15:16:16 27 4
gpt4 key购买 nike

我为我的 Http 模块创建了以下类型:

export type HttpPromise<TData> = Promise<HttpPromiseSuccess<TData>>
export type HttpPromiseSuccess<TData> = {
config: object;
headers: object;
request: XMLHttpRequest;
status: number;
statusText: string;
data: TData;
}

假设我有以下两种类型:

export type User = {
id: number;
name: string;
...
}
export type ApiError = {
error: string;
statusCode: number;
}

我通常会这样做:

const promise: HttpPromise<User> = Http.get('/api/users/1');
promise
.then(response => {
// response.data is now of type `User`
});

但是我的 API 实际上可以返回错误类型 ApiError 所以我希望 response.dataUser 类型或类型API 错误。我试过了

const promise: HttpPromise<User | ApiError> = Http.get('/api/users/1');
// But now response.data only contains the union of the two type

我也试过

const promise: HttpPromise<User> = Http.get('/api/users/1');
promise
.then(response => {
if ('error' in response.data) {
const payload = response.data as ApiError;
}
});

但这不能进行转换。我有哪些选择?不幸的是,我无法控制 API; API 将始终返回 200,但如果有效负载包含 error,则它将有一个包含代码的 statusCode

最佳答案

您可以使用 user defined typeguard .

typeguard 本身看起来像这样:

const isError = <T>(response: T | ApiError): response is ApiError => {
return !!(response as ApiError).data.error;
};

这将返回一个 bool 值 - 如果响应是一个错误则返回 true,否则返回 false。您的请求处理程序可以是:

const promise: HttpPromise<User | ApiError> = Http.get('/api/users/1');
promise
.then(response => {
if (isError(response)) {
// response typed as ApiError
} else {
// response typed as User
}
});

因为类型保护是通用的,所以这也适用于其他响应类型:

const promise: HttpPromise<BlogPost | ApiError> = Http.get('/api/users/1');
promise
.then(response => {
if (isError(response)) {
// response typed as ApiError
} else {
// response typed as BlogPost
}
});

关于javascript - 更改有效载荷的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44420801/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com