
Runtime Introspection of Flow Types in JS - joe-stanton
https://medium.com/p/runtime-introspection-of-flow-types-ddb7e5b042a5?repost=true
======
phpnode
Cool article. I'm the author of [https://github.com/codemix/babel-plugin-
typecheck](https://github.com/codemix/babel-plugin-typecheck) mentioned and
the next version of the plugin (WIP) takes this kind of approach, so that you
can reference a type at runtime:

    
    
        type User = {name: string, isAdmin: boolean};
    
        // compiles to
        const User = t.object(
          t.property('name', t.string()),
          t.property('isAdmin', t.boolean())
        );
    
        // which you can then use with
        User.check({name: 'Alice'}); // boolean
        User.assert({nom: false}); // throws
    
    

Ultimately it should be possible to use this to implement pattern matching in
JS based on flow types, for example:

    
    
        type User = {
          name: string;
          roles: Role[];
        };
    
        type Role = {
          id: number;
          name: string;
          users: User[]
        };
    
        const url = match(someInput, 
          (user: User) => `/users/${user.name}`,
          (role: Role) => `/roles/${role.id}`,
          (_) => `/` // default URL
        );
    

The really hard thing is to do this whilst maintaining perfect compatibility
with flow.

------
zdragnar
This is really neat! You may want to also look at
[https://github.com/gcanti/babel-plugin-
tcomb](https://github.com/gcanti/babel-plugin-tcomb) for some inspiration-
I've used tcomb extensively for runtime ADT and typing, but using just Flow
would be an interesting challenge!

