简体   繁体   中英

Why does the react 18.2 tutorial throws TS2339 Property 'X' does not exist on type 'Readonly<{}>'

I am currently following the react tutorial but at one point I am getting the TS2339 Property 'value' does not exist on type 'Readonly<{}>' error

class Board extends React.Component {
  renderSquare(i) {
    return <Square value={i} />;
  }
}

class Square extends React.Component {
  render() {
    return (
      <button className="square">
        {this.props.value}
      </button>
    );
  }
}

Why do I get this error, but the tutorial is working fine? I know how to fix it by eg adding the properties to the class or by using an interface.

class Square extends React.Component<{value: string}, {}> {
    render() {
        return (
        <button className="square">
            {this.props.value}
        </button>
        );
    }
}


class Square extends React.Component<ISquare> {
    render() {
        return (
        <button className="square">
            {this.props.value}
        </button>
        );
    }
}

interface ISquare {
  value: string;
}

But why do I need to change something on my side? As far as I see the tutorial is using the same React version.

Why do I get this error, but the tutorial is working fine?

Because that is a JavaScript tutorial, not a TypeScript tutorial, and there is no type validation in JavaScript.

Trying to do React.Component<{value: string}, {}> in a JavaScript file would be a syntax error.

But why do I need to change something on my side? As far as I see the tutorial is using the same React version.

Because you're using TypeScript and not JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM