簡體   English   中英

msal typescript 錯誤屬性 'accessToken' 不存在於類型 'void | 令牌響應'

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

下面的代碼為response.accessToken生成以下 TypeScript 錯誤:

TS2339:類型“void |”上不存在屬性“accessToken” 令牌響應”。 在此處輸入圖像描述

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

在檢查 TokenResponse 的TS 定義時,它清楚地指出屬性accessToken在 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;
};

我究竟做錯了什么?

盡管您正在使用await ,但請注意您的catch 我會這樣寫這段代碼:

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

現在,為什么您的response變得void 有可能 function acquireTokenPopup對於acquireTokenSilentgetTokenPopup都會失敗。 因此,function getTokenPopup將拋出錯誤(或不返回任何內容,取決於您的實現)。

TypeScript 看到了這一點,並添加了一個void類型以指示有可能無法得到響應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM