Home > Software engineering >  How to specify using generics/type hints one specific subtype of a type union?
How to specify using generics/type hints one specific subtype of a type union?

Time:02-18

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.

CodePudding user response:

You just need a type constraint on X:

type Creator<X extends C> = () => X;

Playground Link

  • Related