React组件中history对象类型定义问题:如何避免使用any[]
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

