mgfjx
mgfjx

Reputation: 71

How to inherit component in react native with typescript?

I wrote a BaseListPage component like this:

export default class BaseListPage extends Component<Props, State> {

and, I want to write another component inherited BaseListPage, like this:

export default class DynamicListPage extends BaseListPage<Props, State> {

but it prompts Type 'BaseListPage' is not generic..

I'm a new typescripter in react-native, please help!

Upvotes: 3

Views: 1171

Answers (2)

Matt Wills
Matt Wills

Reputation: 726

It's because you're passing type arguments to your BaseListPage class with the BaseListPage<Props, State> part of class DynamicListPage extends BaseListPage<Props, State>, but the class doesn't accept any type arguments.

You can let BaseListPage take type arguments by making it a 'generic':

class BaseListPage<Props, State> extends Component<Props, State> {

see - https://www.typescriptlang.org/docs/handbook/generics.html


Since a react component could have any shape of props or state, those type arguments allow you to define exactly what they will look like for a given instance of a class, allowing you to run the necessary type checks.

Eg.

 interface Props {
   foo: string
 }

 class MyComponent extends Component<Props> {
   render() {
     console.log(this.props.foo) // Fine
     console.log(this.props.bar) // Error

     ...
   }
 }

So either, define the exact Props and State that a BaseListPage component can have like so, thereby removing the need for it to be generic:

 interface BaseListPageProps {
   foo: string
 }

 interface BaseListPageState {
   bar: string
 }

 class BaseListPage extends Component<BaseListPageProps, BaseListPageState> {
   ...
 }

 class DynamicListPage extends BaseListPage {
  render() {
     console.log(this.props.foo) // Fine
     console.log(this.state.bar) // Fine

     console.log(this.props.bar) // Error

     ...
   }
 }

or let it be generic, allowing the DynamicListPage to decide the Props and State types:

 class BaseListPage<Props, State> extends Component<Props, State> {
   ...
 }

 interface DynamicListPageProps {
   foo: string
 }

 interface DynamicListPageState {
   bar: string
 }

 class DynamicListPage extends BaseListPage<DynamicListPageProps, DynamicListPageState> {

Better yet, compose via composition, not inheritance. https://reactjs.org/docs/composition-vs-inheritance.html

Upvotes: 1

sebbab
sebbab

Reputation: 1046

Use

export default class DynamicListPage extends BaseListPage {

instead of

export default class DynamicListPage extends BaseListPage<Props, State> {

That should be enough to make your code work as you expected.

More info about this topic can be found here: https://www.typescriptlang.org/docs/handbook/generics.html

Upvotes: 0

Related Questions