Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

typescript - Bind radio group to a boolean value using svelte

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

question from:https://stackoverflow.com/questions/65841762/bind-radio-group-to-a-boolean-value-using-svelte

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a number, like:

<script lang="ts">
    export let firstSelected = true;
    
    let group
    
    $: group = firstSelected ? 1 : 0
</script>

<input type="radio" bind:group={group} value={1}/>
<input type="radio" bind:group={group} value={0}/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...