mobx-state-tree
mobx-state-tree copied to clipboard
Union dispatcher snapshot undefined
Question
- [x] I've checked documentation and searched for existing issues
- [ ] I tried the spectrum channel
In our MST/Typescript project we like to use Model.is(...) quite a bit, this sometimes results in errors like these popping up:
Cannot read property 'exampleProperty' of undefined
1 | dispatcher: (snapshot) => snapshot.exampleProperty || types.null,
| ^
This is usually caused by not enforcing the passed model to be non-nullable via an extra check like:
exampleObject && Model.is(exampleObject)
It's easily fixed but not always caught by people due to the rather "mysterious" error thrown and no typing error.
Is there a way to enforce Model.is to throw type errors with undefined values? Would this be something that MST would have to change in their typings or maybe the inference is already there but I am not using it correctly. (I'd be happy to create an PR).
Hey @vallode - sorry it took anyone so long to get back to you here in the MST project.
Unfortunately I don't have an answer for you at the moment, but I will add some labels to help us as we clean up the maintenance overall, and hopefully we can get this slated for a fix.
I know it's been literally years, so I understand if you aren't interested/have moved on, but did you ever find a fix on your own? Are you still interested in submitting a PR? We're definitely open to improvements in the typing system.
Hey, no worries. I'd have to try and dig out the codebase this was a part of in order to look back into it, I remember the issue being quite simple.
Changing:
dispatcher: (snapshot) => snapshot.exampleProperty || types.null,
To:
dispatcher: (snapshot) => snapshot?.exampleProperty ?? types.null,
Would likely resolve this, happy to open a PR and play around with it but give me a little time ;)
Thanks for getting back so quickly @vallode!
Take all the time you need. For now, I'm going to assign this to you so folks know someone might be working on it. If you ever decide you don't have the time, let me know or unassign yourself. We still have plenty of cleanup to do, so I'm not rushing to review any PRs just yet.
I'll probably check in sometime in the coming weeks about it.
Thanks again!