Issue
I want to create a svelte component that exports a boolean value that can be binded and represents the state of a radio button group, like the following code:
<script lang="ts">
export let firstSelected = true;
</script>
<input type="radio" bind:group={firstSelected} value={true}/>
<input type="radio" bind:group={firstSelected} value={false}/>
The problem with this is that svelte-check
issues the errors:
Error: Type 'true' is not assignable to type 'string | number | string[]'. (ts)
Error: Type 'false' is not assignable to type 'string | number | string[]'. (ts)
A possible fix is to use a number instead of a boolean, however this changes the interface of the component:
<script lang="ts">
export let firstSelected = 1;
</script>
<input type="radio" bind:group={firstSelected} value={1}/>
<input type="radio" bind:group={firstSelected} value={0}/>
Is there a way to fix this while still exposing a bindable boolean value? If not, is there a way to ignore this error?
REPL with example: https://svelte.dev/repl/b6e9042a1b594f2bb77b1e8e7b38ffe1?version=3.31.2
Solution
Using another number variable together with a reactivity declaration and a on:change
handler fixes the problem:
<script lang="ts">
export let firstSelected = true;
$: _firstSelected = Number(firstSelected);
function handleChange(e) {
firstSelected = Boolean(_firstSelected);
}
</script>
<input type="radio" bind:group={_firstSelected} value={1} on:change={handleChange}/>
<input type="radio" bind:group={_firstSelected} value={0} on:change={handleChange}/>
Answered By - Tyilo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.