cambiata
cambiata
SSolidJS
Created by cambiata on 5/29/2024 in #support
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:
type UnionType = { type: 'Empty' } | { type: 'Data', value: number };

const App: Component = () => {
const [state, setState] = createSignal<UnionType>({ type: 'Empty' });
return <>
<p>{JSON.stringify(state())}</p>
<button onClick={_ => setState({ type: 'Data', value: 123 })}>Set</button>

<Switch fallback={<div>Fallback</div>}>
<Match when={state().type = 'Empty'}>
<div>Type is 'Empty'</div>
</Match>
<Match when={state().type === 'Data'}>
<div>Type is 'Data': data={state().value}</div> // <-- 'value' does not exist...
</Match>
</Switch>
</>
};
type UnionType = { type: 'Empty' } | { type: 'Data', value: number };

const App: Component = () => {
const [state, setState] = createSignal<UnionType>({ type: 'Empty' });
return <>
<p>{JSON.stringify(state())}</p>
<button onClick={_ => setState({ type: 'Data', value: 123 })}>Set</button>

<Switch fallback={<div>Fallback</div>}>
<Match when={state().type = 'Empty'}>
<div>Type is 'Empty'</div>
</Match>
<Match when={state().type === 'Data'}>
<div>Type is 'Data': data={state().value}</div> // <-- 'value' does not exist...
</Match>
</Switch>
</>
};
The error output:
Property 'value' does not exist on type 'UnionType'.
Property 'value' does not exist on type '{ type: "Empty"; }'.ts(2339)
Property 'value' does not exist on type 'UnionType'.
Property 'value' does not exist on type '{ type: "Empty"; }'.ts(2339)
12 replies