How to call a sub component's method from a main component in React with Typescript?
<p>I'm trying to access a component as itself so that I could call its methods, but I haven't been successful at it.</p>

<p>I've a simple <code>TestComponent</code> which has a <code>print()</code> method in it. I want to call that <code>print()</code> method from <code>MainComponent</code>. So I did something like this:</p>

<pre><code>class TestComponent extends React.Component&lt;IProps, IState) {

   print() {
      console.log('From TestComponent');
   }

   render() {
      return &lt;h1&gt;Item&lt;/h1&gt;;
   }
}

class MainComponent extends React.Component&lt;IProps, IState) {

   private list:Array&lt;TestComponent&gt;;   //This is going to throw an error in Typescript. It expects type of JSX Element.

   render() {
      for(let i=0; i&lt;5; i++) list.push(&lt;TestComponent/&gt;);   //&lt;TestComponent&gt; is recognised as a JSX element instead so this will throw an error
      list.forEach((component) =&gt; component.print());   //Since this is JSX Element, calling print() will throw unknown function print() error.
      return &lt;h1&gt;Main Component&lt;/h1&gt;{list};
   }
}
</code></pre>

<p>It turns out that I cannot use <code>TestComponent</code> as the object type in Typescript. I have to set the type of my <code>list</code> array to be of <code>JSX.Element</code> for it to work. But if I do so, I cannot "up-cast" the type to call <code>TestComponent</code>'s <code>print()</code> method from <code>MainComponent</code>.</p>

<p>So, how can I call a sub component's method from a main component which contains the sub component?</p>

<p>And, in Typescript, how should I define my component's type?</p>