Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion - readonly state proxy #66

Closed
benallfree opened this issue Jul 8, 2023 · 2 comments
Closed

Suggestion - readonly state proxy #66

benallfree opened this issue Jul 8, 2023 · 2 comments

Comments

@benallfree
Copy link

This is more a dx issue, but I see a pattern frequently where I'd like to be able to bind to a state var, but prevent accidental writes to it because writes should be handled by a helper that adjusts multiple state variables or performs other side effects. It would be nice to have something like State.readonly() that returned a wrapped version where get stateVar.val worked but set stateVar.val threw an exception.

It might look something like this:

  "readonly"() {
    let _this=this
    return { 
      ..._this,
      set "val"(v) { throw new Error(`State is read-only`) },
    }
  }
export type State<T> = {
  val: T
  onnew(l: (val: T, oldVal: T) => void): void
  readonly(): State<T> & { readonly val:T}
}

Or, if you don't want to actually add that to the code, I can basically get what I need from TS type checking

export type ReadOnlyState<T> = Omit<State<T>, 'val'> & { readonly val: T }
export const toReadOnlyState = <T>(state: State<T>) => state as ReadOnlyState<T>
@Tao-VanJS
Copy link
Member

I think StateView<T> is exactly the TypeScript type that you're looking for.

@Tao-VanJS
Copy link
Member

Also, I think you can have a readonly(s: State<T>) helper function by your own.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants