Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static class function access issue withRouter typescript react

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.

like image 516
Hardik Chaudhary Avatar asked Aug 14 '26 16:08

Hardik Chaudhary


1 Answers

Maybe not elegant but I fixed this by recasting:

export default withRouter(MyComponent) as unknown as typeof MyComponent;
like image 181
user5480949 Avatar answered Aug 16 '26 20:08

user5480949



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!