Reputation: 45454
For example, in vanilla JS I could easily do something like this:
class BaseClass extends React.Component { ... }
class Foo extends BaseClass { ... }
ReactDOM.render(<Foo />, someEl)
and it just works, no problem.
However, I can't seem to do such a simple thing in TypeScript. I tried to do
class BaseClass<P,S> extends React.Component<P,S> { ... }
interface IFooProps {...}
interface IFooState {...}
class Foo extends BaseClass<IFooProps, IFooState> { ... }
ReactDOM.render(<Foo />, someEl)
but that fails with errors like
ERROR in ./src/app.tsx
(44,17): error TS2605: JSX element type 'Foo' is not a constructor function for JSX elements.
Property 'setState' is missing in type 'Foo'.
ERROR in ./src/app.tsx
(44,17): error TS2607: JSX element class does not support attributes because it does not have a 'props' property
ERROR in ./src/Foo.tsx
(30,49): error TS2339: Property 'props' does not exist on type 'Foo'.
My question is, how do we extend React.Component
in order to make a base class where child classes of the base class can still specify the types of their props and state, so that I can do
class Foo extends BaseClass<IFooProps, IFooState> { ... }
where BaseClass
extends from React.Component
?
Upvotes: 1
Views: 1648
Reputation: 276269
The following code is perfectly fine:
class BaseClass<P,S> extends React.Component<P,S> { ... }
and works fine e.g. I use it to add custom behavior to my React components in alm : https://github.com/alm-tools/alm/blob/5ff516f0212f75c7365a56104413d34dddcbf429/src/app/ui.tsx#L11
Upvotes: 1