我正在尝试使用 fetch 和 typescript 创建发布请求。 但无法创建 204 状态处理程序。
我已经尝试返回空值的 promise ,但它不起作用。
postRequest = async <T>(url: string, body: any): Promise<T> => {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(body)
});
// here is my problem
if (response.status === 204) {
// error is: "Type 'null' is not assignable to type 'T'."
return null;
// I have tried to return promise, but it doesn't work.
// error is: "Argument of type 'null' is not assignable to
// parameter of type 'T | PromiseLike<T> | undefined'."
return new Promise(resolve => resolve(null));
}
if (!response.ok) {
throw new Error(response.statusText);
}
return await response.json() as Promise<T>;
};
postRequest<{data: boolean}>('request', { someValue: 1234 });
最佳答案
使用 Union Type表示 Promise<T>
或 Promise<null>
返回:
postRequest = async <T>(url: string, body: any): Promise<T | null> => {
在这个例子中,返回类型是Promise<T | null>
, 这表示 T
或 null
将用于已解决的 promise 。
关于javascript - 如何使用 Typescript 和 fetch 处理 204 状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57938929/