'How to specify using generics/type hints one specific subtype of a type union?

How can I create a function type Creator<X> that will only allow creating A or Bs while keeping the quality that you know which type you get?

This is not what I want:

type C = A|B
type Creator = () => C; // requires a type predicate for type safety

Using type predicates, one can discern whether a value qualifies as one type or another. That puts some extra work on the consumer of the interface I would like to avoid. Instead I would like a client that is to implement the interface to say

export creator : Creator<A> = () => return new A(); // should be OK! 

while disallowing

export creator : Creator<number> = () => return 42; // NOT OK! 

I have a TS Playground setup to make playing around with this easy.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source