Variable is used before being assigned with fetch

Viewed 329

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

If there is a scenario where you don't return a valid OrganizationResponseInfo and you don't throw an error, you should / would have to change the return type to be nullable. => Promise<OrganizationResponseInfo?>

As I mentioned in comment, you are assigning value to your organizationInfoResponse variable inside try-catch block, and then you have return at the end of your function. In case it catches error, your variable will not get any value assigned to it, therefore it cannot be returned. You simply need to assign some value to it on declaration

Related