3

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.

2
  • 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, and not a React one. If that's not possible I'd try using the React ref as explained here stackoverflow.com/questions/24841855/…. Commented Apr 10, 2020 at 7: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.) Commented Jan 22, 2021 at 1:22

1 Answer 1

1

Maybe not elegant but I fixed this by recasting:

export default withRouter(MyComponent) as unknown as typeof MyComponent;
Sign up to request clarification or add additional context in comments.

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.