简体   繁体   中英

msal typescript error Property 'accessToken' does not exist on type 'void | TokenResponse'

The code below generates the following TypeScript error for the response.accessToken :

TS2339: Property 'accessToken' does not exist on type 'void | TokenResponse'. 在此处输入图像描述

import * as Msal from '@azure/msal-browser'

export async function getTokenPopup(request: Msal.TokenExchangeParameters) {
  return await auth.acquireTokenSilent(request).catch(async () => {
    return await auth.acquireTokenPopup(request).catch((error) => {
      console.log('login with popup failed: ', error)
    })
  })
}

const getGraphDetails = async (
  uri: string,
  scopes: Msal.TokenExchangeParameters,
  axiosConfig?: AxiosRequestConfig
) => {
  return getTokenPopup(scopes).then((response) => {
      return callGraph(uri, response.accessToken, axiosConfig)
  })
}

When checking the TS definition of TokenResponse it clearly states that the property accessToken is available on the object:

export type TokenResponse = AuthResponse & {
    uniqueId: string;
    tenantId: string;
    scopes: Array<string>;
    tokenType: string;
    idToken: string;
    idTokenClaims: StringDict;
    accessToken: string;
    refreshToken: string;
    expiresOn: Date;
    account: Account;
};

What am I doing wrong?

Just a note regard your catch , although you are using await . I'd write this code like so:

import * as Msal from '@azure/msal-browser'

export async function getTokenPopup(request: Msal.TokenExchangeParameters) {
    try {
        return await auth.acquireTokenSilent(request);
    } catch (error) {
        return await auth.acquireTokenPopup(request);
    }
}

const getGraphDetails = async (
    uri: string,
    scopes: Msal.TokenExchangeParameters,
    axiosConfig?: AxiosRequestConfig
) => {
    try {
        const response = await getTokenPopup(scopes);
        return callGraph(uri, response.accessToken, axiosConfig);
    } catch (error) {
        throw new Error("You could not get a token");
    }
}

Now, why you are getting void in response . There is a possibility, that function getTokenPopup will fail both for acquireTokenSilent and acquireTokenPopup . So that, the function getTokenPopup will throw an error (or return nothing, depends on your implementation).

TypeScript sees that and add a void type to indicate that there is a possibility to not get a response back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM