0

I have a class that extends the React.Component class and I'm passing it my own interface for the props that I expect to receive. The problem is that when I use the SomeComponent.propTypes = {... the webstorm linter says something is wrong, stating that Property 'propTypes' does not exist on type 'typeof SomeComponent'.

I have no Idea why that happends....

the code of SomeComponent is

class SomeComponent extends React.Component<IProps, {}> {...}

A similar exception is thrown when I write the following code to create a functional component:

const SomeComponent: React.FunctionComponent<IProps> = (props) => {...}

In this case, again I'm getting an error when using the SomeComponent.propTypes = {...} syntax... this time the exception is type ... is not assignable to type ....\

Any help on why it happens and how to tell typescript that I should be able to use this property? Thanks!

1 Answer 1

3

Typescript doesn't allow adding static properties after declaring the class. I believe you can add propTypes by adding it as a static property in the class:

class SomeComponent extends React.Component<IProps, {}> {
  static propTypes = {} // Set your propTypes here
}

Aside, why do you want to use propTypes when you are using Typescript? TS will take care of the type checking at compile time.

Sign up to request clarification or add additional context in comments.

3 Comments

The reason for using propTypes in addition to the interface of the props is that propTypes is checking at runtime, and typescript is for compile time. As for the answer you gave to my question, does that also apply to a functional component? because when I use the syntax function SomeComponent(props: IProps) {...} And then I use the SomeComponent.propTypes = {...} it works, so what are the rules exactly?
Afaik Typescript allows adding "static properties" to functions, but not to classes. So this should also work: const SomeComponent = (props: IProps) => {...}; SomeComponent.propTypes = {...}.
If you correctly type your interfaces you should remove the need to have prototypes also. It seems like unnecessary developer outlay..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.