You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React JS转TS:dataContext创建函数的类型错误求助

React Context 创建函数的TypeScript迁移问题解决方案

错误原因

你的Provider组件参数定义有误:React组件接收的是props对象,而非直接的children值。你当前将参数写成(children: ReactNode),但实际React会传入{ children: ReactNode }结构的对象,导致类型不兼容,触发报错。

基础修复方案

先修正Provider的参数类型,让它接收包含children的props对象:

import React, { useReducer, createContext, ReactNode } from 'react'

export default (reducer: any, actions: any, defaultValue: any) => {
    const Context = createContext(defaultValue)

    // 修正:解构props对象,并指定children的类型
    const Provider = ({ children }: { children: ReactNode }) => {
        const [state, dispatch] = useReducer(reducer, defaultValue)

        const boundActions: any = {}
        for (let key in actions) {
            boundActions[key] = actions[key](dispatch)
        }

        return (
            <Context.Provider value={{state, ...boundActions}}>
                {children}
            </Context.Provider>
        )
    }

    return {Context, Provider}
}

也可以用React内置的PropsWithChildren类型简化定义:

const Provider = ({ children }: React.PropsWithChildren<{}>) => {

进阶优化:用泛型替代any(推荐)

为了让类型更安全,避免使用any,可以引入泛型来约束状态、reducer和动作的类型:

import React, { useReducer, createContext, ReactNode, Dispatch, Reducer } from 'react';

// 泛型约束:State为状态类型,Actions为动作对象类型
export default function createDataContext<State, Actions extends Record<string, (dispatch: Dispatch<any>) => any>>(
  reducer: Reducer<State, any>,
  actions: Actions,
  defaultValue: State
) {
  // 定义Context的类型为状态+动作的组合
  const Context = createContext<State & Actions>({} as State & Actions);

  const Provider = ({ children }: React.PropsWithChildren<{}>) => {
    const [state, dispatch] = useReducer(reducer, defaultValue);

    const boundActions = {} as Actions;
    for (const key in actions) {
      boundActions[key] = actions[key](dispatch);
    }

    return (
      <Context.Provider value={{ ...state, ...boundActions } as State & Actions}>
        {children}
      </Context.Provider>
    );
  };

  return { Context, Provider };
}

泛型的作用

  • State:指定Context中状态的具体类型,使用时会自动推断并提供类型提示
  • Actions:约束动作对象的结构,确保每个动作都是接收dispatch并返回函数的格式
  • 这样整个创建函数在使用时会具备完整的类型检查,避免潜在的类型错误。

内容的提问来源于stack exchange,提问作者asfarasiknow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 03:26:12