Robert Chen
Robert Chen

Reputation: 43

TS2339: Property X does not exist on type '{}'

I can't seem to resolve this error.

ERROR in App.tsx(9,15) TS2339: Property 'count' does not exist on type '{}'.

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;

My tsconfig is as follows,

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

I'm also using webpack to build the app. I'm loading the typescript with 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"
  }

Thanks!

Upvotes: 4

Views: 5169

Answers (2)

kingdaro
kingdaro

Reputation: 12028

Install the React type definitions:

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

Without the types installed, TS can't properly infer the props needed for JSX elements. Hopefully they'll make the error a little clearer in the future c:

Upvotes: 5

alegria
alegria

Reputation: 1155

Adding the following to the Test component seems to work.

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

As to why, here's an explanation to the solution.

Another explanation from another answer :

super allows you to access the constructor method of the parent class. The only reason to include props is to access this.props inside of your constructor.

Upvotes: 0

Related Questions