【发布时间】:2021-08-16 14:40:21
【问题描述】:
Typescript 在我的函数的倒数第二行抛出以下错误:
变量“organizationInfoResponse”在被分配之前使用。
我不太确定如何忽略这个问题,因为我在 fetch 的 try catch 块内分配了 organizationInfoResponse。请您在这里指出正确的方向吗?
interface OrganizationInfoResponse {
organization_name: string;
organization_id: string;
errorCode?: string;
}
export const handleGetOrganization = async (
organizationName: string,
): Promise<OrganizationInfoResponse> => {
let organizationInfoResponse: OrganizationInfoResponse;
try {
const rawRes = await fetch(
`/sometestendpoint/${organizationName}`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
},
);
organizationInfoResponse = await rawRes.json();
if (rawRes.status >= 400) {
if (organizationInfoResponse.errorCode === ErrorCodes.INVALID_ORG_NAME) {
throw new Error('Given Organization Name is invalid');
}
}
} catch (error) {
// Do something
}
return organizationInfoResponse;
};
【问题讨论】:
-
尝试像
let organizationInfoResponse: OrganizationInfoResponse | undefined = undefined那样为organizationInfoResponse 赋值。您正在设置它的值 try-catch 块,因此可能存在捕获的情况,然后您尝试返回未分配的值 -
这是应该在 Typescript 中解决的方式,还是处理这些错误的“hacky”方式。
-
我更新了评论并解释了案例。这不是一个 hacky 解决方案 :)
-
这是否意味着我需要将返回的类型更新为
Promise<OrganizationInfoResponse | undefined>?如果我不这样做,我可以看到Type 'undefined' is not assignable to type 'OrganizationInfoResponse'.。 -
是的,就是这个意思。您需要更新返回值,因为如果它捕获,将返回 undefined
标签: javascript typescript