3

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!

1

2 Answers 2

1

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

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

Comments

0

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

Comments

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.