Support for discriminated union types?
Being new to SolidJS, I'm surprised to find that the type checking for discriminated union types in
signals or stores seems to be limited. See example below.
From my perspective this is very problematic.
Am I missing something? Are there any decent workarounds? Plans for support?
In the following example, the type checker complains about the the missing
state().value
field,
in spite of the state().type === 'Data'
being matched in the Switch statement:
The error output:
7 Replies
the problem is rather that jsx on itself will not narrow types.
https://docs.solidjs.com/reference/components/show has a callback form that can help with type-narrowing
you can also use the keyed version
https://docs.solidjs.com/reference/components/switch-and-match#lessswitchgreater-lessmatchgreater
<Match/>
also seems to support a callback as a child, but I am less familiar with <Match/>
Do note that I'm pretty sure keyed causes rerenders from what I remember.
Match
has the same options as Show, keyed and non-keyed callbacks for childrenThanks guys! Found what seems to be a decent solution in this thread: https://discord.com/channels/722131463138705510/1074415945986080808/1074415948137758750
Here's an example:
No
keyed
involved, so perhaps no performance penalties.Yes the callback form should be good!
If anyone's interested, here's a gist that shows how to deal with discriminated unions both in the view rendering and in the store:
Gist
Displays a way to deal with discriminated union types in Solid-js, ...
Displays a way to deal with discriminated union types in Solid-js, jsx view as well as store - Discriminated unions in Solid.js.tsx
https://discord.com/channels/722131463138705510/734440921776783391/1237768818340659211 this might be of interest to u too