paldepind / union-type

A small JavaScript library for defining and using union types.
MIT License
477 stars 28 forks source link

How to enumerate thru all type variants #34

Open avesus opened 8 years ago

avesus commented 8 years ago

There is a convenient case() function which allows to switch on precise type. But for library code it is very useful to enumerate thru all type keys.

const Action = Type({
  Walk: [],
  Run: []
});

Action.forEach(name => console.log(name));

should output

Walk
Run
paldepind commented 8 years ago

What is your use case for this?

avesus commented 8 years ago

As long as union-type can work as what in VisualBasic/Microsoft terminology called by word 'Variant', it should be possible to know every kind of types which it could have. For an example, in testing by passing all variant types instances. The case() function only allows us to switch on exact already passed variant, but not dynamically determine which other variants it may have.

My particular use case is in a framework, where I implement multilevel plugins inheritance of components, and it's necessary to know all parent's types to effectively match wich parts the child overrides/extends.

I can submit a patch, if you'll find that useful and confirm on the API. Sure, some sort of the Array operations should be supported, so, may be some variantKeys() function which work like Object's keys(). Or types(), which sound more concisely IMO.

The task is just to filter out the case and caseOn elements from the Type's keys() method call resulting array. My current solution is very ugly and depends on type variants names capitalization. Otherwise, excluding the method names in the client code is like a hell when you'll add new methods ;-)