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

TypeScript报错:Property 'detail' does not exist on type '{}'.ts(2339) 如何修复?

如何修复React Router跳转时的TypeScript类型错误?

Hey there! Let's work through that TypeScript error you're facing with your React Router code. I've looked at your snippets, and the root issue is that TypeScript can't infer the type of location.state—plus, there's a risk that state might be undefined if someone navigates directly to the target page instead of using your link.

Here's how to fix it step by step:

1. First, Define a Type for Your State

Start by creating an interface that describes the structure of the state you're passing between pages. This gives TypeScript clear rules to follow.

// You can put this in a shared types file or at the top of your component
interface PageNavigationState {
  detail: string | number; // Adjust this to match your actual id type (e.g., number if ids are numeric)
}

2. Update the Navigation Code

In the component where you're using useHistory, add the type to the push method to ensure you're passing the correct state shape:

import { useHistory } from "react-router-dom";

interface PageNavigationState {
  detail: string | number;
}

const YourSourceComponent = () => {
  const history = useHistory();
  const id = 123; // Replace with your actual id value

  // Example function to trigger navigation
  const goToOtherPage = () => {
    // Add the type to history.push to enforce state structure
    history.push<PageNavigationState>({
      pathname: '/otherPage',
      state: { detail: id }
    });
  };

  return <button onClick={goToOtherPage}>Go to Other Page</button>;
};

3. Fix the Target Page Code

In the target page, use the same type with useLocation, and always check if state exists before accessing its properties (this prevents runtime errors too!):

import React, { useEffect } from 'react';
import { useLocation } from "react-router-dom";

interface PageNavigationState {
  detail: string | number;
}

const OtherPage = () => {
  // Attach our state type to useLocation
  const location = useLocation<PageNavigationState>();

  useEffect(() => {
    // Always check if state exists first (critical for direct URL visits)
    if (location.state) {
      console.log(location.state.detail);
    } else {
      // Handle the case where state is missing (e.g., show an error message)
      console.warn("No state data found—did you navigate directly to this page?");
    }
  }, [location]);

  return <div>Welcome to the Other Page!</div>;
};

export default OtherPage;

Bonus: Use a Type Guard for Extra Safety

If you want to be extra rigorous (great for larger apps), you can add a type guard to validate that the state matches your expected structure:

import React, { useEffect } from 'react';
import { useLocation } from "react-router-dom";

interface PageNavigationState {
  detail: string | number;
}

// Type guard to validate state structure
const isValidNavigationState = (state: unknown): state is PageNavigationState => {
  return (
    typeof state === 'object' &&
    state !== null &&
    'detail' in state &&
    (typeof (state as PageNavigationState).detail === 'string' || typeof (state as PageNavigationState).detail === 'number')
  );
};

const OtherPage = () => {
  const location = useLocation();

  useEffect(() => {
    if (isValidNavigationState(location.state)) {
      console.log(location.state.detail);
    } else {
      console.warn("Invalid or missing navigation state");
    }
  }, [location]);

  return <div>Welcome to the Other Page!</div>;
};

export default OtherPage;

This approach not only fixes the TypeScript error but also makes your code more robust against unexpected navigation scenarios.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 08:02:29