React类组件转TypeScript时触发TS2339属性不存在报错
报错核心成因
- 类组件继承
React.Component时未传入自定义Props作为泛型参数,导致类内部所有对this.props的访问默认使用基类内置的空泛型定义,也就是报错中展示的Readonly<{}> & Readonly<{ children?: ReactNode; }>类型,不会识别你单独给constructor方法标注的Props类型。 - 现有自定义
TodoItemProps接口字段覆盖不全,仅定义了title、completed两个属性,组件实际用到的id、toggleTodo、removeTodo三个属性未纳入类型定义。
修复方案
- 补全
TodoItemProps接口的全部字段,为每个字段匹配对应的实际类型:id:匹配实际传入的标识类型(一般为number或string)toggleTodo:匹配方法签名,即接收id作为入参、无返回值的函数removeTodo:匹配对应方法签名
- 将补全后的Props接口作为泛型参数传入
Component基类,让TypeScript在整个组件作用域内关联自定义的props类型定义。
修复后可正常运行的代码
import React, { Component } from 'react' interface TodoItemProps { title: string, completed: boolean, id: number | string, toggleTodo: (id: number | string) => void, removeTodo: (id: number | string) => void, } // 核心修复:给Component传入Props泛型 export default class TodoItem extends Component<TodoItemProps> { constructor(props: TodoItemProps) { super(props); this.handleToggle = this.handleToggle.bind(this); this.handleRemove = this.handleRemove.bind(this); } handleToggle() { const { toggleTodo, id } = this.props; 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> ) } }
关键注意事项
- 该方案完全保留原有业务逻辑,仅补充类型检查相关定义,不需要调整原有组件的运行逻辑。
- 仅在constructor方法上标注Props类型不会触发全局类型推导,必须通过给
Component基类传入泛型的方式,才能让类内所有方法、渲染逻辑中的this.props匹配自定义类型。
内容的提问来源于stack exchange,提问作者Michael Durrant
相关产品推荐
相关产品推荐

