2

I have one react component and based on routing props change I am performing some actions. I have one static function in the class but typescript not getting the class properties.

I am exporting component as withRouter(MyComponent) and I want to access static property of component MyComponent.myStaticMethod().

How can I use appropriate typings for this. I am strictly following typescript so I don't want use type any. Below is a sample code.

class MyComponent extends React.Component<RouteComponentProps>{
  public static myStaticMethod():void{
     console.log("myStaticMethod called");
  }

  public render(): JSX.Element {
     return // something;
  }

  // some other life cycle methods with required logic
}

export default withRouter(MyComponent);

But it is giving an error when I am trying to access static method MyComponent.myStaticMethod()

Property 'myStaticMethod' does not exist on type 'ComponentClass<Pick<RouteComponentProps<{}, StaticContext, any>, never>, any>'..

It is working fine with type any ((MyComponent as any).myStaticMethod()) but I don't want to use any.

Hardik Chaudhary
  • 1,200
  • 1
  • 8
  • 24
  • If you want to call methods from the outside, I'd try re-thinking the design so that you can utilize a regular [javascript class](https://developer.mozilla.org/sv-SE/docs/Web/JavaScript/Reference/Classes), and not a React one. If that's not possible I'd try using the React ref as explained here https://stackoverflow.com/questions/24841855/how-to-access-component-methods-from-outside-in-reactjs. – gqstav Apr 10 '20 at 07:31
  • OP was trying to use a _static_ method, not an instance method (which would require a ref). (Sorry, OP, I was looking for an answer to this same question, so I don't know the solution.) – Adam DiCarlo Jan 22 '21 at 01:22

1 Answers1

0

Maybe not elegant but I fixed this by recasting:

export default withRouter(MyComponent) as unknown as typeof MyComponent;
user5480949
  • 1,410
  • 1
  • 15
  • 22