title: How to type hint an object of unknown child class, but known parent class?
body: <p>This is Python 3.10. My code is as follows:</p>
  <pre><code>from __future__ import annotations
  from typing import Union
  
  class Vehicle():
  
      def __init__(self, components):
          self.components = components
  
      def getComponentWithFlag(self, flag: str) -&gt; Union[Component,None]:
          for component in self.components:
              if getattr(component,flag,None):
                  return component
          return None
  
  
  class Component():
      pass
  
  
  class PassengerComponent(Component):
  
      def __init__(self):
          self.carriesPassengers = True
  
      def ejectPassenger(self):
          print('A passenger is tossed outside!')
  
  
  class FreightComponent(Component):
  
      def __init__(self):
          self.carriesFreight = True
  
  
  VW_Mini = Vehicle(components= [PassengerComponent()])
  VW_Passat = Vehicle(components= [PassengerComponent(), FreightComponent()])
  Truck = Vehicle(components= [FreightComponent()])
  
  assert VW_Mini.getComponentWithFlag('carriesPassengers')
  assert not VW_Mini.getComponentWithFlag('carriesFreight')
  assert Truck.getComponentWithFlag('carriesFreight')
  assert not Truck.getComponentWithFlag('carriesPassengers')
  
  component = VW_Mini.getComponentWithFlag('carriesPassengers')
  component.ejectPassenger()
  </code></pre>
  <p>Last line gives me a warning in PyCharm: <code>Cannot find reference 'ejectPassenger' in 'Component | None'.</code> I understand why it happens: there is no <code>ejectPassenger</code> method in Component class. Clearly the problem lies in how I typehint <code>Vehicle.getComponentWithFlag</code> method. Could you guys tell me how I should type hint its return object?</p>
  <p>I know the object returned by that function:</p>
  <ul>
  <li>may be None (if there's no appropriate Component),</li>
  <li>may be an object of a subclass inheriting from <code>Component</code> class,</li>
  <li>will never actually be an object of <code>Component</code> class itself.</li>
  </ul>
  <p>Type hinting it explicitly like this: <code>def getComponentWithFlag(self, flag: str) -&gt; Union[PassengerComponent, FreightComponent, None]</code> will not fly, because I will eventually have dozens of Components in my actual use-case and I would prefer to avoid typing them all out.</p>