React Context中TypeScript上下文值类型不匹配错误排查
React Context TypeScript类型错误解决
错误信息
Type '{ createReferral: (referralData: { actionStepId: number; appTypeId: string; comment: string; createdDate: Date; createdBy: string; createdByDisplayName: string; currentAssigneeDisplayName: string; ... 4 more ...; submissionId: string; }) => void; getCurrentUser: () => AccountInfo; }' is not assignable to type 'SelectedContextType'.
问题原因
类型不匹配的核心点在getCurrentUser函数:
- 你定义的
SelectedContextType接口中,getCurrentUser要求返回仅包含name和username的对象 - 但实际返回的
msalContext.accounts[0]被TypeScript推断为AccountInfo类型(MSAL库自带的类型定义),该类型包含更多字段,和预期类型不兼容。
解决方案
方案1:严格返回预期结构
修改getCurrentUser函数,只提取需要的字段返回,确保和接口定义完全匹配:
function getCurrentUser() { const account = msalContext.accounts[0]; return { name: account.name, username: account.username }; }
方案2:更新接口以匹配实际返回类型
如果需要使用msalContext.accounts[0]的其他字段,可以直接复用MSAL的AccountInfo类型,或者手动定义对应结构:
复用MSAL自带类型
先导入MSAL的类型:
import { AccountInfo } from "@azure/msal-react"; interface SelectedContextType { createReferral: (referralData: { actionStepId: number appTypeId: string comment: string createdDate: Date createdBy: string createdByDisplayName: string currentAssigneeDisplayName: string currentAssigneeGRNID: string reasonTypeId: number | string referralTypeId: number | string statusTypeId: number submissionId: string }) => void getCurrentUser: () => AccountInfo }
手动定义结构
如果不想导入MSAL类型,直接根据实际返回结构定义接口:
interface AccountInfo { authorityType: string; environment: string; homeAccountId: string; idTokenClaims: { aud: string }; localAccountId: string; name: string; username: string; } interface SelectedContextType { createReferral: (referralData: { actionStepId: number appTypeId: string comment: string createdDate: Date createdBy: string createdByDisplayName: string currentAssigneeDisplayName: string currentAssigneeGRNID: string reasonTypeId: number | string referralTypeId: number | string statusTypeId: number submissionId: string }) => void getCurrentUser: () => AccountInfo }
内容的提问来源于stack exchange,提问作者user11631308
相关产品推荐
相关产品推荐

