在我的 Svelte 4 应用中,我动态加载了组件,所有组件都有不同的 props。非常简单的复制(也可在Svelte Playground上使用):
// App.svelte
<script lang="ts">
import One from "./One.svelte";
import Two from "./Two.svelte";
import type { ComponentType } from "svelte";
type Item = {
component: ComponentType;
};
const items: Item[] = [
{ component: One, one: "World" },
{ component: Two, two: "Svelte" },
];
</script>
<div class="container py-20 text-white">
{#each items as item}
<div>
<svelte:component this={item.component} {...item} />
</div>
{/each}
</div>
// One.svelte
<script lang="ts">
export let one;
</script>
Hello {one}
// Two.svelte
<script lang="ts">
export let two;
</script>
Goodbye {two}
运行良好,没有任何警告或错误,到目前为止没有任何投诉。但是我想迁移到 Svelte 5,现在我收到一堆 TypeScript 错误。例如ComponentType
已弃用,以及类似以下内容:
Type '__sveltets_2_IsomorphicComponent<{ one: any; }, { [evt: string]: CustomEvent<any>; }, {}, {}, string>' is not assignable to type 'ComponentType'.
Type '__sveltets_2_IsomorphicComponent<{ one: any; }, { [evt: string]: CustomEvent<any>; }, {}, {}, string>' is not assignable to type 'new (options: ComponentConstructorOptions<Record<string, any>>) => SvelteComponent<Record<string, any>, any, any>'.
Types of parameters 'options' and 'options' are incompatible.
Type 'ComponentConstructorOptions<Record<string, any>>' is not assignable to type 'ComponentConstructorOptions<{ one: any; }>'.
Property 'one' is missing in type 'Record<string, any>' but required in type '{ one: any; }'.
我该如何重构代码,使其继续工作,而不会出现 TypeScript 错误,并且不必对每个组件进行强类型化?在我的实际应用中,涉及许多组件,每个组件都有一大堆不同的 props。我不想为每个组件创建类型别名。
只需更改ComponentType
为Component
即可消除弃用警告,但其他警告基本仍然相同:
Type '__sveltets_2_IsomorphicComponent<{ one: any; }, { [evt: string]: CustomEvent<any>; }, {}, {}, string>' is not assignable to type 'Component<{}, {}, string>'.
Types of parameters 'props' and 'props' are incompatible.
Type '{}' is not assignable to type '{ one: any; } & { $$events?: { [evt: string]: CustomEvent<any>; } | undefined; $$slots?: {} | undefined; }'.
Property 'one' is missing in type '{}' but required in type '{ one: any; }'.ts(2322)
更改ComponentType
为SvelteComponent
也不会让事情变得更好。当我使用该unknown
类型时,我收到此警告:
Argument of type 'unknown' is not assignable to parameter of type 'ConstructorOfATypedSvelteComponent | Component<any, any, any> | null | undefined'.
至少那只是一个警告,而不是数组中的一大堆,所以更好,但这真的不能用更好的方法解决吗(无需输入每个组件)?