【问题标题】:TS2339: Property X does not exist on type '{}'TS2339:类型“{}”上不存在属性 X
【发布时间】:2019-01-11 20:56:46
【问题描述】:

我似乎无法解决此错误。

App.tsx(9,15) 中的错误 TS2339:类型“{}”上不存在属性“count”。

App.tsx

import React from "react";

import Test from "./Test";

const App = () => {
  return (
    <div>
      <Test count={1} />
    </div>
  );
}

export default App;

Test.tsx

import React from "react";

interface Props{
  count: number
}
interface State{}

class Test extends React.Component<Props, State>{
  render(){
    return <div>{this.props.count}</div>;
  }
}

export default Test;

我的tsconfig如下,

{
  "compilerOptions": {
    "allowJs": true,
    "jsx": "react",
    "module": "es6",
    "target": "es5",
    "allowSyntheticDefaultImports": true
  },
  "include": ["src"]
}

我也在使用 webpack 来构建应用程序。 我正在使用ts-loader 加载打字稿

package.json

  "dependencies": {
    "axios": "^0.18.0",
    "express": "^4.16.3",
    "fetch": "^1.1.0",
    "less": "^3.8.0",
    "mathjax": "^2.7.5",
    "node-html-parser": "^1.1.8",
    "react": "^16.4.2",
    "react-dom": "^16.4.2",
    "webpack": "^4.16.3"
  },
  "devDependencies": {
    "@types/express": "^4.16.0",
    "classnames": "^2.2.6",
    "css-loader": "^1.0.0",
    "less-loader": "^4.1.0",
    "nodemon": "^1.18.3",
    "style-loader": "^0.21.0",
    "ts-loader": "^4.4.2",
    "ts-node": "^7.0.0",
    "typescript": "^3.0.1",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.5"
  }

谢谢!

【问题讨论】:

  • 如果你改写"include": ["./src/**/*"],你会得到同样的错误吗?
  • @Tholle 是的,它仍然输出相同的错误
  • 这令人沮丧。您能否在问题中包含您的整个 App.tsxTest.tsx 文件?
  • @Thole 我已经更新了问题
  • 谢谢。很奇怪。 It works for me.

标签: reactjs typescript


【解决方案1】:

安装 React 类型定义:

npm install -D @types/react @types/react-dom

如果没有安装类型,TS 无法正确推断 JSX 元素所需的道具。希望他们以后能把错误弄得更清楚一点 c:

【讨论】:

  • 啊,我明白了。这现在更有意义了!谢谢!
【解决方案2】:

将以下内容添加到Test 组件似乎可行。

constructor(props: Props){ super(props); }

至于为什么,here 是对解决方案的解释。

另一个answer的解释:

super 允许你访问父类的构造方法。包含 props 的唯一原因是在构造函数中访问 this.props。

【讨论】:

    猜你喜欢
    • 2016-11-14
    • 2021-08-10
    • 1970-01-01
    • 2016-03-14
    • 2017-02-25
    • 1970-01-01
    相关资源
    最近更新 更多