You need to enable JavaScript to run this app. React类组件转TypeScript时触发TS2339属性不存在报错
优惠活动
大模型
产品
解决方案
定价
更多

React类组件转TypeScript时触发TS2339属性不存在报错

报错核心成因
  • 类组件继承React.Component时未传入自定义Props作为泛型参数,导致类内部所有对this.props的访问默认使用基类内置的空泛型定义,也就是报错中展示的Readonly<{}> & Readonly<{ children?: ReactNode; }>类型,不会识别你单独给constructor方法标注的Props类型。
  • 现有自定义TodoItemProps接口字段覆盖不全,仅定义了title、completed两个属性,组件实际用到的id、toggleTodo、removeTodo三个属性未纳入类型定义。
修复方案
  1. 补全TodoItemProps接口的全部字段,为每个字段匹配对应的实际类型:
    • id:匹配实际传入的标识类型(一般为number或string)
    • toggleTodo:匹配方法签名,即接收id作为入参、无返回值的函数
    • removeTodo:匹配对应方法签名
  2. 将补全后的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.12.05 23:45:04