javascript - 转换 React 项目时出现 Typescript 错误

标签 javascript reactjs typescript

这是特定于我正在从标准 ES2015 转换为 Typescript 的 React 应用程序。在我的 .tsx 文件(从常规 .js 文件转换而来)中,我遇到了一些我不知道如何解决的 typescript 错误。

第一个是:error TS2339: Property 'propTypes' does not exist on type 'typeof App'.

这适用于:

App.propTypes = {
  actions: PropTypes.object.isRequired,
  fuelSavingsAppState: PropTypes.object.isRequired
};

我尝试在定义 App 的代码之上创建一个接口(interface),例如:

interface App {
    propTypes?: any;
}

但这没有任何效果。显然我是 Typescript 的新手,所以我错过了什么?

另一个错误是:

error TS2605: JSX element type 'Element' is not a constructor function for JSX elements.
  Property 'render' is missing in type 'Element'

这适用于:

{settings.necessaryDataIsProvidedToCalculateSavings ? <FuelSavingsResults savings={settings.savings} /> : null}

错误具体指关于<FuelSavingsResults的位

完全不知道从哪里开始。欢迎提出任何建议。


如果有帮助,FuelSavingsResults 的定义开头如下:

let FuelSavingsResults = (props) => {
    let savingsExist = NumberFormatter.scrubFormatting(props.savings.monthly) > 0;
    let savingsClass = savingsExist ? 'savings' : 'loss';
    let resultLabel = savingsExist ? 'Savings' : 'Loss';

然后有一个常规的 React 渲染方法,但我认为这无关紧要。

最佳答案

error TS2339: Property 'propTypes' does not exist on type 'typeof App'.

代替

class App extends React.Component{
}
App.propTypes = {
  actions: PropTypes.object.isRequired,
  fuelSavingsAppState: PropTypes.object.isRequired
};

使用static 属性。

class App extends React.Component{
    static propTypes = {
      actions: PropTypes.object.isRequired,
      fuelSavingsAppState: PropTypes.object.isRequired
    };
}

error TS2605: JSX element type 'Element' is not a constructor function for JSX elements. Property 'render' is missing in type 'Element'

这是编译器中的一个错误,现已修复:https://github.com/Microsoft/TypeScript/issues/6349替代方案为 props 提供类型注释。 🌹

关于javascript - 转换 React 项目时出现 Typescript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34779183/

相关文章:

javascript - 如何根据 typescript 显示的动态条件更改图标?

javascript - TypeScript合并Function接口(interface),扩展Function原型(prototype)

javascript - 如何在字符串中搜索多个值?

node.js - CocoaPods找不到Pod "lottie-ios"的兼容版本

typescript - Mongoose 预存给我红线?

javascript - .Map函数差异javascript typescript

javascript - Jquery 用户界面 : How can I update id on drop event

javascript - unitPngFix 防止更改隐藏的 "display"的 "div"

javascript - react 16 : Call children's function from parent when using hooks and functional component

reactjs - 可以篡改 react 状态以绕过安全措施吗?