关于 Svelte 组件中 TS2322 错误的问题
Question about TS2322 error in Svelte Component
我正在使用 TypeScript 学习 Svelte。
我在这段代码中遇到 TS23
错误。
<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)
此错误发生在 input
标记的 value
属性中。
我该如何处理?我真的不知道这个。
Typescript 表示单选输入的 value
属性只能是字符串、数字或字符串数组 (string | number | string[]
)。假设 name
是唯一的,您可以改用名称作为值。这将需要更多的工作来将名称映射回组件,但这是非常小的。
此示例将无线电输入绑定到 selectedName
,并设置一个响应式语句以在 selectedName
更新时查找关联的组件。
<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}
我正在使用 TypeScript 学习 Svelte。
我在这段代码中遇到 TS23
错误。
<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)
此错误发生在 input
标记的 value
属性中。
我该如何处理?我真的不知道这个。
Typescript 表示单选输入的 value
属性只能是字符串、数字或字符串数组 (string | number | string[]
)。假设 name
是唯一的,您可以改用名称作为值。这将需要更多的工作来将名称映射回组件,但这是非常小的。
此示例将无线电输入绑定到 selectedName
,并设置一个响应式语句以在 selectedName
更新时查找关联的组件。
<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}