Typescript结合Context API实现主题切换报类型不匹配错误如何解决?
问题原因
你触发的TS报错本质是类型定义和实际实现不匹配,对应核心问题如下:
- 你在
themeContext接口中声明的SwitchTheme类型是无参数函数() => void,但实际实现的SwitchTheme要求传入1个参数,两者类型不一致直接触发了2322报错 - 除此之外你的代码还存在3处关联的逻辑/类型错误需要同步修复:
themeContext接口定义的主题字段是dark,但Provider传值、reducer修改的字段都是darktheme,字段名完全不匹配- 你调用
SwitchTheme时传入的是布尔值true,但函数参数声明的是string类型,参数类型冲突 defaultState中dark字段的类型被写死为false字面量,后续无法修改为true,需要改为boolean类型
修复代码
Context逻辑修复
// Context + State Logic import React, { createContext, useReducer } from 'react'; import ModalReducer from './modalReducer'; // 修正接口类型定义 interface themeContext { darktheme: boolean; // 修正SwitchTheme的参数类型,和实际调用、实现保持一致 SwitchTheme?: (status: boolean) => void; } // 修正默认值字段和类型 const defaultState: themeContext = { darktheme: false, }; // Create context export const AppStateContext = createContext<themeContext>(defaultState); export const SET_THEME = 'SET_THEME'; // 给组件props补充children类型 const AppStateProvider: React.FC<{children: React.ReactNode}> = ({ children }) => { const [state, dispatch] = useReducer(ModalReducer, defaultState); // 修正参数类型为boolean,和调用逻辑一致 const SwitchTheme = (status: boolean) => { dispatch({ type: SET_THEME, state: status, }); }; return ( <AppStateContext.Provider value={{ darktheme: state.darktheme, SwitchTheme, }} > {children} </AppStateContext.Provider> ); }; export default AppStateProvider;
Reducer逻辑(可选类型优化)
// Reducer Logic import { SET_THEME } from './AppState'; import type { themeContext } from './AppState'; // 补充action类型定义 type ActionType = { type: typeof SET_THEME, state: boolean } export default (state: themeContext, action: ActionType) => { switch (action.type) { case SET_THEME: return { ...state, darktheme: action.state, }; default: return state; } };
原有组件内的调用代码无需修改,即可正常运行。
内容的提问来源于stack exchange,提问作者Richardson
相关产品推荐
相关产品推荐

