1

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

TS2339: Property 'accessToken' does not exist on type 'void | TokenResponse'. enter image description here

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?

4

1 回答 1

1

尽管catch您正在使用await. 我会这样写这段代码:

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

现在,你为什么void进来response。有一种可能性,该功能对于和getTokenPopup都将失败。因此,该函数将引发错误(或不返回任何内容,取决于您的实现)。acquireTokenSilentacquireTokenPopupgetTokenPopup

TypeScript 看到了这一点并添加了一个void类型来表明有可能没有得到响应。

于 2020-05-25T12:17:57.840 回答