我使用@azure/msal-react和@azure/msal-browser来实现与类型记录反应的身份验证。
我的问题是,event.payload被TypeScript知道为EventPayload (union)类型,但是它不允许我使用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)
...
}
}
...
});发布于 2022-07-07 14:28:52
您应该显式地检查event.payload,并且不能使用instanceof,因为ts不知道您在运行时的类型。因为在事件处理程序中使用回调。
建议添加辅助函数,演示
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
}
}
}https://stackoverflow.com/questions/72899431
复制相似问题