Search code examples
reactjstypescriptsyntax-error

Passing data through props with react+ts


Im trying to do the quick start tutorial from here: https://react.dev/learn/tutorial-tic-tac-toe in ts instead of js. whats wrong? it says: 'number' is declared but its value is never read.ts(6133) Binding element 'number' implicitly has an 'any' type.ts(7031)

export default function Board(){
  return (
    <>
      <div className="board-row">
        <Square value={1}/>
        <Square value={2}/>
        <Square value={3}/> 
      </div>
      <div className="board-row">
        <Square value={4}/>
        <Square value={5}/>
        <Square value={6}/>
      </div>
      <div className="board-row">
        <Square value={7}/>
        <Square value={8}/>
        <Square value={9}/>
      </div>
    </>
  );
}

function Square({value: number}){
  return <button className="square">{value}</button>;
}

it says: 'number' is declared but its value is never read.ts(6133) Binding element 'number' implicitly has an 'any' type.ts(703


Solution

  • In your example, you are using destructuring.

    function Square({value: number}) {
      // ...
    }
    // is equivalent to:
    function Square({ value: number }: any) {
      // ...
    }
    // or
    function Square(props: any) {
      const number = props.value;
    
      // ...
    }
    
    
    // what you want is providing the type for the props:
    function Square({ value }: { value: number }) {
     // ...
    }
    
    // or
    interface SquareProps {
      value: number;
    }
    
    function Square({ value }: SquareProps) {
     // ...
    }
    
    // which is equivalent to:
    function Square(props: SquareProps) {
     const value = props.value;
     // ...
    }
    

    Good luck with your learning journey!