属性在类型"Readonly<{}> & Readonly<{ children?: ReactNode; }>"中不存在。TS2339



在尝试将文件转换为typescript时,出现了上述错误

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

作为dev依赖项。

不知道如何修复这个

目前,您还没有告诉typescript这个组件需要什么道具,所以它默认为一个空对象{}。您确实在构造函数中放入了一个类型,但这不是将其应用于整个类的正确位置。

要修复它,请更改此:

export default class TodoItem extends Component {

对此:

export default class TodoItem extends Component<TodoItemProps> {

最新更新