0kku / destiny

A reactive UI library for JavaScript and TypeScript
Open Software License 3.0
53 stars 6 forks source link

Implicit recursive conversion of objects #9

Open 0kku opened 4 years ago

0kku commented 4 years ago

For convenience, JSON-like structures are recursively converted to become reactive. However, TypeScript's type system can't tell plain objects from other ones. Support for nominal typing would help, but I wouldn't hold my breath on that ever getting implemented in TS. As a consequence, this is awful for DX, because objects unexpectedly breaking inside reactive structures.

Possible solutions:

  1. Don't convert objects This would be quite inconvenient in terms of DX, but might be the cleanest solution.

  2. Flagging objects One solution would be to make it mandatory to add a property to objects that acts as a "flag" for intent to be converted. This is almost as much work for developers as not converting objects at all, while being ugly.

  3. Modify the original object Conceivably, it should be possible to add a symbol property on objects, which would serve as a key for accessing reactive properties:

    
    import { 
    reactive,
    reactiveObjectSymbol, // is a Symbol; probably would need a more reasonable name
    } from "destiny-ui";

const obj = new SomeObject; const reactiveObj = reactive(obj);

console.log(obj === reactiveObj); // true: it adds the symbol property onto the original object, and returns it console.log(obj[reactiveObjectSymbol]); // logs the reactive version of the input object


This seems to be the best of both worlds, even if it feels a bit dirty.