简体   繁体   中英

How to define specific return type of react method (typescript)

I want to define a return type of a specific react component.

For Example:

Component 1

class ComponentFoo extends React.Component<any, any> {
   public render() {…}
}

Component 2

class ComponentBar extends React.Component<any, any> {
    public renderComponentFoo() : ComponentFoo { <---
      return <ComponentFoo />
    }

    public render() {
      …
      {this.renderComponentFoo()}
      …
    }
}

Is something like this possible?

Your renderComponentFoo method should return React.ReactNode instead.

JSX/TSX is just syntax sugar around React.createElement() which returns React.ReactNode . You are not returning an instance of ComponentFoo as your current code suggests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM