Msal React TypeScript开发:未声明AccountInfo类型致useState报错求助
Msal-React 类型错误解决及AccountInfo类型说明
类型错误修复
你遇到的是TypeScript类型不匹配问题:useState初始值为null,默认推断类型是null,但后续传入的AccountInfo类型无法匹配。只需显式为useState指定联合类型即可解决:
import { AccountInfo } from "@azure/msal-browser"; const [currentUser, setCurrentUser] = useState<AccountInfo | null>(null); const msal = useMsal(); const isAuthenticated = useIsAuthenticated(); useEffect(() => { if (isAuthenticated) { msal.instance.handleRedirectPromise().then(() => { const allAccounts = msal.instance.getAllAccounts(); console.log(allAccounts); if (allAccounts.length > 0) setCurrentUser(allAccounts[0]); }); } }, [isAuthenticated]);
AccountInfo类型结构说明
AccountInfo是@azure/msal-browser库导出的核心类型,用于描述已认证用户的账户信息,核心字段包括:
homeAccountId: string —— 全局唯一账户ID,格式为租户ID.用户对象IDusername: string —— 用户的邮箱或登录用户名name?: string—— 用户的全名(可选)tenantId: string —— 用户所属的Azure AD租户IDidTokenClaims?: Record<string, any>—— ID令牌中包含的所有声明,比如用户角色roles、邮箱email、用户IDsub等idToken: string —— 原始的ID令牌字符串environment: string —— 认证环境地址,比如login.microsoftonline.com
内容的提问来源于stack exchange,提问作者user11631308
相关产品推荐
相关产品推荐

