首页 > 解决方案 > Variable is used before being assigned with fetch

问题描述

Typescript throws the following error on the second last line of my function:

Variable 'organizationInfoResponse' is used before being assigned.

I am not too sure how to omit that problem since I am assigning the organizationInfoResponse inside a try catch block in a fetch. Can you point me in the right direction here please?

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;
};

标签: javascripttypescript

解决方案


正如我在评论中提到的,您organizationInfoResponse在 try-catch 块中为变量赋值,然后在函数结束时返回。如果它捕获错误,您的变量将不会获得分配给它的任何值,因此无法返回。您只需要在声明时为其分配一些值


推荐阅读