thefrontside / microstates

Composable state primitives for JavaScript
1.31k stars 53 forks source link

How to get Type of a microstate? #273

Open taras opened 5 years ago

taras commented 5 years ago

We don't have a way to get the Type of a Microstate. This makes it difficult when I want to be able to serialize a Microstate where the microstate went through a few transitions. Especially when the microstate might have gone a type change via set. We have metaOf, valueOf but not typeOf.

cowboyd commented 5 years ago

microstate.constructor.Type

taras commented 5 years ago

I will test it but I believe there were some weird edge cases. Should we make typeOf that does microstate.constructor.Type?

cowboyd commented 5 years ago

Actually, we probably need to return the type that create was called with before any type changes happen.

let light = create(TrafficLight, 'green');
light.constructor.Type //=> class GreenLight {}'
typeOf(light) //=> TrafficLight
taras commented 5 years ago

How do we do that?

cowboyd commented 5 years ago

I'm not exactly sure how aside from making union types first-class citizens.

cowboyd commented 5 years ago

Upon reflection, I think we need to have ways to access them all. We can start storing the Type on the meta of each microstate. Where Type is the intended, and potentially abstract type of the microstate.

import { typeOf } from 'microstates';

let five = create(Maybe(Number), 5);
typeOf(five) //=> Maybe<Number>
five.constructor.Type //=> Just<Number>

let anulled = five.set(null);
typeOf(anulled) //=> Maybe<Number>
annulled.constructor.Type //=> Nothing
cowboyd commented 5 years ago

Worth noting that subatomic microstate rely on storing the original Type https://github.com/microstates/lab/blob/master/src/meta.js#L40-L42

So when / if this makes it into master, there will be a typeOf(microstate) operation on every microstate.