Search code examples
javascriptnode.jstypescriptasync-awaites6-promise

How do I return only type of resolve in a Promise?


let companyInfo: PublicCompanyAPIResponseType;
companyInfo = await get<PublicCompanyAPIResponseType>({
    url: getCompanyDataURL,
}).catch(res => {
    responseStatus = res.status;
});

When i assign companyInfo variable to that get func

export async function get<T>({ url, headers }: ApiConnectSet): Promise<T> {
return new Promise((resolve, reject) => {
    fetch(url, {
        method: 'GET',
        credentials: 'same-origin',
        headers: headers,
    })
        .then(async res => {
            if (res.ok) {
                return resolve((await res.json()) as Promise<T>);
            } else if (res.status === 401) {
                const redirectPath = window.location.pathname;
                window.location.href =
                    '/login?redirectPath=' + redirectPath;
            } else {
                reject(res);
            }
        })
        .catch(error => {
            reject(error);
        });
});

}

Visual studio code shows this error enter image description here

How can my get function only return PublicCompanyAPIResponseType?


Solution

  • try this, if it works

    let companyInfo: PublicCompanyAPIResponseType;
    try {
      companyInfo = await get<PublicCompanyAPIResponseType>({
        url: getCompanyDataURL,
      })
    } catch(err => {
        // get the status from error object and assign it to response status
        responseStatus = // your status code
    });