justin-schroeder / arrow-js

Reactivity without the framework
https://arrow-js.com
MIT License
2.32k stars 50 forks source link

TypeScript type for nested, optional reactive objects is broken #68

Open irskep opened 1 year ago

irskep commented 1 year ago

Let's say I make this reactive object:

interface State {
  x?: { y: number };
}

const state = reactive<State>({x: { y: 0 }});

And then I want to observe the value of x.y:

state.x?.$on('y', (val) => console.log(val));

I get a TypeScript error:

Property '$on' does not exist on type '{ y: number; }'

I recognize this example code won't work if the initial value of x is undefined, but if it's present, .$on works fine, so it would be nice if the type system reflected this.

justin-schroeder commented 1 year ago

Yeah this is unfortunately true. Sadly there is no way (at the moment) to define different types on setting vs getting with proxy objects (see: https://github.com/microsoft/TypeScript/issues/43826). I'll leave this open to encourage us to look into it further as other options arise.