简体   繁体   中英

Property does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'. TS2339

In trying to convert a file to typescript I get the above error for

handleToggle() {
  const { toggleTodo, id } = this.props;    // <-- Error
  toggleTodo(id);
}

I have tried several things such as adding attributes to the interface I added for this component, adding binding statements, adding methods for those attributes, etc. However they all give errors, often the above. To just add typescript checking it seems like I shouldn't need to make a lot of changes though. The other similar questions and answers I saw here didn't help. For instance I added these items to the interface props but still got an error.

The code I have so far (which was working fine before this conversion) is

import React, { Component } from 'react'

interface TodoItemProps { // Added this interface for props
  title: string,
  completed: boolean,
}
export default class TodoItem extends Component {
  constructor(props:TodoItemProps) { // used inteface from abovereact 
    super(props);
    this.handleToggle = this.handleToggle.bind(this);
    this.handleRemove = this.handleRemove.bind(this);
  }
  handleToggle() {
    const { toggleTodo, id } = this.props; // < -- errors here.
    toggleTodo(id);
  }
  handleRemove() {
    const { removeTodo, id } = this.props;
    removeTodo(id);
  }
  render() {
    const { title, completed } = this.props;
    return (
      <div style={{ width: 400, height: 25 }} >
        <input
          type="checkbox"
          checked={completed}
          onChange={this.handleToggle} />
        {title}
        <button style={{ float: 'right' }} onClick={this.handleRemove}>x</button>
      </div>
    )
  }
}

I do have

@types/react
@types/react-node

as dev dependencies.

No sure how to fix this

Currently, you havn't told typescript what props this component takes, so it defaults to an empty object {} . You did put a type in the constructor, but that's not the right place to apply it to the entire class.

To fix it, change this:

export default class TodoItem extends Component {

To this:

export default class TodoItem extends Component<TodoItemProps> {

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