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

如何解决React中TypeScript的「请勿使用`object`类型」错误?

解决@typescript-eslint/ban-types禁止使用object类型的问题

你的代码第18行的<P extends object>触发了@typescript-eslint/ban-types规则,原因是object类型在TypeScript中存在使用不便的问题,比如无法直接安全访问属性、类型收窄操作繁琐。

你可以用以下几种类型替代:

  • Record<string, unknown>:这是ESLint提示的首选方案,明确表示“键为字符串类型、值为未知类型的对象”,既能满足props是对象的约束,又能更灵活地处理属性检查:

    export const withRouter = <P extends Record<string, unknown>>(Component: ComponentType<P>) => {
    
  • { [key: string]: unknown }:和上面的Record<string, unknown>完全等价,是另一种写法:

    export const withRouter = <P extends { [key: string]: unknown }>(Component: ComponentType<P>) => {
    
  • Record<PropertyKey, unknown>:如果你的组件props可能包含数字或符号类型的键,可以用这个更宽泛的类型,PropertyKey是TypeScript内置的string | number | symbol联合类型:

    export const withRouter = <P extends Record<PropertyKey, unknown>>(Component: ComponentType<P>) => {
    

修改后的完整代码示例:

import { ComponentType } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";

export interface WithRouterProps<T = ReturnType<typeof useParams>> {
    history: {
        back: () => void;
        goBack: () => void;
        location: ReturnType<typeof useLocation>;
        push: (url: string, state?: any) => void;
    };
    location: ReturnType<typeof useLocation>;
    match: {
        params: T;
    };
    navigate: ReturnType<typeof useNavigate>;
}

export const withRouter = <P extends Record<string, unknown>>(Component: ComponentType<P>) => {
    return (props: Omit<P, keyof WithRouterProps>) => {
        const location = useLocation();
        const match = { params: useParams() };
        const navigate = useNavigate();

        const history = {
            back: () => navigate(-1),
            goBack: () => navigate(-1),
            location,
            push: (url: string, state?: any) => navigate(url, { state }),
            replace: (url: string, state?: any) =>
                navigate(url, {
                    replace: true,
                    state,
                }),
        };

        return (
            <Component
                history={history}
                location={location}
                match={match}
                navigate={navigate}
                {...(props as P)}
            />
        );
    };
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 23:36:08