首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何检查在联合类型中定义的值的类型?

如何检查在联合类型中定义的值的类型?
EN

Stack Overflow用户
提问于 2022-07-07 14:16:16
回答 1查看 68关注 0票数 0

我使用@azure/msal-react@azure/msal-browser来实现与类型记录反应的身份验证。

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

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

代码语言:javascript
复制
import {
  EventType,
  AuthenticationResult,
  PublicClientApplication,
} from "@azure/msal-browser";
代码语言:javascript
复制
export declare type EventPayload = AccountInfo | PopupRequest | RedirectRequest | SilentRequest | SsoSilentRequest | EndSessionRequest | AuthenticationResult | PopupEvent | null;
代码语言:javascript
复制
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)
      ...   
    }
  }
  ...
});
EN

回答 1

Stack Overflow用户

发布于 2022-07-07 14:28:52

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

建议添加辅助函数,演示

代码语言:javascript
复制
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
    }
  }
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72899431

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档