QED0711 / spiccato

MIT License
0 stars 1 forks source link

Custom setters that call this.setState(prevState) require a type to be explicitly set #26

Closed navarrotech closed 1 month ago

navarrotech commented 3 months ago

While testing with Spiccato, I ran into an issue:

manager.addCustomSetters({
  setThing(thing: Thing) {
    this.setState((prevState) => { // <-- Here! prevState in Typescript doesn't know what type prevState is

The short term workaround is to:

// Before
this.setState((prevState)

// After
this.setState((prevState: State)

However, this now also requires the State type to be in every scope where your custom setters are defined.

I think typescript should be able to know that type through the class.

QED0711 commented 3 months ago

This is partially resolved in the release-1.0.4-beta branch. If you do this:

myManager.setState((prevState) => {
    /* you get type safety of prevState here without having to explicitly type prevState */
})

Where this still wont work (see comments on issue #25) is if you define some function outside the scope of the manager (i.e. in another file where the manager is referenced as this like in custom setters). The this keyword in these scenarios will have a limited type inference to the actual instance of the manager itself. It will know what other getters/setters/methods exist in the structure, but it won't be able to automatically infer the type structure of prevState. For this, you will still need to type prevState yourself.

As captured in issue #25, using the CLI will produce a file structure and necessary type exports that takes much of the difficulty out of this pattern.

Unless there are other concerns, this issue will be closed when the beta branches are merged into the main branch.