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

React组件中history对象类型定义问题:如何避免使用any[]

Fixing the history Type in Your React Game Component

Got it, let's replace that any[] with a proper, type-safe definition for your history state! Here's how to do it step by step:

1. Define a Type for Individual History Steps

First, create an interface that describes exactly what each entry in the history array contains. Since your initial state has a squares property (an array of 9 null values for tic-tac-toe), we can type that explicitly:

// Define the structure of a single step in your game history
interface GameStep {
  squares: (null | 'X' | 'O')[]; // Each square is either empty, X, or O
}

2. Update Your State Interface

Now use this GameStep type to replace any[] in your GameClass state interface:

interface GameClass {
  history: GameStep[]; // No more `any`!
  stepNumber: number;
  xIsNext: boolean;
}

3. Verify Initial State Compatibility

Your existing initial state in the constructor is already perfectly compatible with this new type:

this.state = {
  history: [{ squares: Array(9).fill(null) }], // Matches GameStep[] exactly
  stepNumber: 0,
  xIsNext: true
};

Bonus: Extensibility

If you later want to add more data to each history entry (like the position of the move), you can simply extend the GameStep interface without breaking type safety:

interface GameStep {
  squares: (null | 'X' | 'O')[];
  movePosition?: { row: number; col: number }; // Optional new property
}

This approach eliminates the use of any, keeps your code type-safe, and makes the structure of your game state clear to anyone reading the code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 19:57:49