【问题标题】:How to check the type of a value being one defined in a union type?如何检查在联合类型中定义的值的类型?
【发布时间】:2022-07-08 16:06:54
【问题描述】:

我使用 @azure/msal-react@azure/msal-browser 在 React with Typescript 中实现身份验证。

我的问题是 TypeScript 知道 event.payload 的类型为 EventPayload(联合),但是它不允许我使用 instanceof 运算符检查确切的类型(例如 AuthenticationResult)。

如何查看event.payload 的确切类型?

import {
  EventType,
  AuthenticationResult,
  PublicClientApplication,
} from "@azure/msal-browser";
export declare type EventPayload = AccountInfo | PopupRequest | RedirectRequest | SilentRequest | SsoSilentRequest | EndSessionRequest | AuthenticationResult | PopupEvent | null;
msalInstance.addEventCallback((event) => {
  if (event.eventType === EventType.LOGIN_SUCCESS) {
    if (event.payload instanceof AuthenticationResult) {
      // 'AuthenticationResult' only refers to a type, but is being used as a value here.ts(2693)
      ...   
    }
  }
  ...
});

【问题讨论】:

    标签: javascript typescript msal


    【解决方案1】:

    你应该显式检查 event.payload,并且你不能使用 instanceof,因为 ts 在运行时不知道你的类型。因为您在事件处理程序中使用了回调

    建议添加辅助功能,demo

    type Base = { // for simplicity add some base type
        eventType: string
    }
    type AuthenticationResult = Base & {
        name: 'auth'
    }
    type PopupEvent = Base & {
        event: string
    }
    
    // helper function that checks type
    function isAuth (evt: EventPayload): evt is AuthenticationResult {
        return evt?.name === 'auth'
    }
    export declare type EventPayload = AuthenticationResult | PopupEvent | null;
    const fn = (event: EventPayload) => {
      if (event?.eventType != null) {
        if (isAuth(event)) {
          // correct type
        }
      }
    }
    

    【讨论】:

    • 这是有道理的。 因为 ts 不知道你在运行时的类型,为什么是它的运行时?,你说的为什么是它的运行时是什么意思?
    • 问题是AuthenticationResult没有name这样的属性。那么,在这种情况下我该如何确定类型呢?
    • 检查 auth 与其他类型有何不同
    猜你喜欢
    • 2020-08-04
    • 2011-03-31
    • 2018-10-09
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多