Home > Software design >  Question about TS2322 error in Svelte Component
Question about TS2322 error in Svelte Component

Time:12-05

I'm studying Svelte with TypeScript.

I faced TS23 error in this code.

<script lang="ts">
    import Test1 from './Test1.svelte';
    import Test2 from './Test2.svelte';

    let components = [
        { name: 'Test1', component: Test1 },
        { name: 'Test2', component: Test2 }
    ];
    let selected;
</script>

{#each components as { name, component } (name)}
    <label><input type="radio" value={component} bind:group={selected} />{name}</label>
{/each}

<svelte:component this={selected} />

Type 'typeof ComponentTest1__SvelteComponent_' is not assignable to type 'string | number | string[]'.

Type 'typeof ComponentTest1__SvelteComponent_' is missing the following properties from type 'string[]': pop, push, concat, join, and 28 more. ts(2322)

This error occurred in the value attribute of the input tag.

How should I handle this? I really do not have an idea of this.

CodePudding user response:

Typescript says that the value attribute of the radio input can only be a string, number, or array of strings (string | number | string[]). Assuming name will be unique, you can use name as the value instead. This will require some more work to map the name back to a component, but it's pretty minimal.

This example binds the radio inputs to selectedName instead, and sets up a reactive statement to find the associated component whenever selectedName is updated.

<script lang="ts">
    import Test1 from './Test1.svelte';
    import Test2 from './Test2.svelte';

    let components = [
        { name: 'Test1', component: Test1 },
        { name: 'Test2', component: Test2 }
    ];
    let selectedName;

    $: selected = components.find((c) => c.name === selectedName);
</script>

{selectedName}
{#each components as { name, component } (name)}
    <label
        ><input type="radio" value={name} bind:group={selectedName} />{name}</label
    >
{/each}

{#if selected}
    <svelte:component this={selected.component} />
{/if}
  • Related