TypeScript中MockState方法返回类型出现可选/undefined问题排查
问题:MockState函数链式调用后返回类型属性被标记为可选
我正在创建一个测试用函数,它返回一个包含模拟状态设置方法的对象。所有类型定义都已完成,但调用链式方法(如mockState().logUser().setStructures(1).test())后,返回结果的类型显示user、ui、structures这些属性都是可选或undefined类型,尽管MockState接口里的test方法明确定义为返回PreloadedState<RootState>。
相关代码定义
MockState接口
interface MockState { structures: StructuresState; ui: UiState; user: UserState; test: () => PreloadedState<RootState>; logUser: () => MockState; setLoadingOn: () => MockState; turnModalOn: (message: string) => MockState; turnErrorModalOn: (message: string) => MockState; setStructures: (total: number) => MockState; }
mockState函数实现
export const mockState = (): MockState => ({ structures: mockStructuresState(), ui: { ...mockUiState }, user: { ...mockUserState }, test() { return { structures: { ...this.structures }, ui: { ...this.ui }, user: { ...this.user }, }; }, logUser() { this.user = { ...loggedUser }; return this; }, setLoadingOn() { this.ui.isLoading = true; return this; }, turnModalOn(message: string) { this.ui.modals = { message, error: false }; return this; }, turnErrorModalOn(message: string) { this.ui.modals = { message, error: true }; return this; }, setStructures(total: number) { this.structures.structures = total === 1 ? [{ ...structures[0] }] : [ { ...structures[0] }, ...Array(total - 1).fill({ ...structures[1] }), ]; return this; }, });
依赖对象定义
const mockUserState: UserState = { isLogged: false, token: "" }; const mockStructuresState = (): StructuresState => ({ structures: [], currentPage: "0", totalPages: 0, totalStructures: 0, }); const mockUiState: UiState = { isLoading: false, modals: { error: false, message: "" }, }; const loggedUser: UserState = { isLogged: true, token: "eyJmsP42OZMDdsrzmY88j1qeHN3mE", }; const structures: StructureStructure[] = [ { elevation: "455", name: "Bassa", type: "Water", id: "7342774", location: "L", image: "https://sfxfnjejl.jpg", owner: "admin", coordenateX: "5689", coordenateY: "56789", creationTime: "56789", description: "its a structure", }, { elevation: "450", name: "Aljub SN08", type: "Construction", id: "7342434774", location: "L", image: "https://sfx.jpg", owner: "admin", coordenateX: "5682329", coordenateY: "567892332", creationTime: "56789233", description: "its another structure", }, ];
TypeScript推断的返回类型
interface typescriptResolution { user?: { token: string; isLogged: boolean } | undefined; ui?: | { isLoading: boolean; modals: { message: string; error: boolean } } | undefined; structures?: {} | undefined; }
我尝试过为mockState函数的返回值指定接口,也给test方法明确了返回类型PreloadedState<RootState>,但问题依然存在。
已解决
问题根源在于测试中使用的PreloadedState本身的属性就是可选的,同时我向render传入的RouterAndState对象用错了属性。RouterAndState接口定义如下:
export interface RouterAndState { ui?: React.ReactElement; preloadedState?: PreloadedState<RootState>; }
内容的提问来源于stack exchange,提问作者lfilella97
相关产品推荐
相关产品推荐

