“ Readonly <{}>和Readonly <{子类型?”上不存在属性: }>'。 TS2339

时间:2020-07-17 22:59:33

标签: reactjs react-proptypes

在尝试将文件转换为打字稿时,出现上述错误

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

我已经尝试了几种方法,例如,向为此组件添加的接口中添加属性,添加绑定语句,为这些属性添加方法等。但是,它们都会产生错误,通常是上述情况。只添加打字稿检查似乎我不需要进行很多更改。我在这里看到的其他类似的问题和答案没有帮助。例如,我将这些项目添加到界面道具中,但仍然出现错误。

到目前为止,我的代码(在此转换之前运行良好)是

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>
    )
  }
}

我有

@types/react
@types/react-node

作为开发依赖项。

不确定如何解决此问题

1 个答案:

答案 0 :(得分:1)

当前,您尚未告诉Typescript该组件需要什么道具,因此它默认为空对象{}。您确实在构造函数中放置了一个类型,但这不是将其应用于整个类的正确位置。

要解决此问题,请更改以下内容:

export default class TodoItem extends Component {

对此:

export default class TodoItem extends Component<TodoItemProps> {