【问题标题】:msal typescript error Property 'accessToken' does not exist on type 'void | TokenResponse'msal typescript 错误属性 'accessToken' 不存在于类型 'void |令牌响应'
【发布时间】:2020-05-25 20:17:57
【问题描述】:

下面的代码为 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 definition 时,它清楚地指出属性 accessToken 在对象上可用:

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

我做错了什么?

【问题讨论】:

  • 请注意,为什么不使用 try/catch 和 await 呢? TypeScript 可能会看到您的 getTokenPopup 返回 void。如果两个 Promise 都失败,则返回 void。
  • 此代码是示例的副本。我只是希望它也可以与 TS 一起使用。

标签: javascript typescript


【解决方案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");
    }
}

现在,为什么你在response 中得到void。有一种可能性是,函数getTokenPopupacquireTokenSilentacquireTokenPopup 都将失败。因此,getTokenPopup 函数将抛出错误(或不返回任何内容,取决于您的实现)。

TypeScript 看到这一点并添加一个 void 类型以表明有可能无法得到响应。

【讨论】:

  • 我刚刚使用async/away 解决方案测试了您的代码,并修复了错误。我必须以这种方式开始工作,因为它也更容易阅读。感谢您的帮助。
  • 似乎 TypeScript 无法使用 catch 正确推断类型,无论如何,很高兴它有所帮助。
猜你喜欢
  • 2019-11-30
  • 1970-01-01
  • 2020-03-25
  • 1970-01-01
  • 2021-05-17
  • 2019-04-26
  • 1970-01-01
  • 2023-02-21
  • 2022-01-27
相关资源
最近更新 更多