使用svelte:component传递组件时,如何解决TypeScript的Props类型报错?
解决Svelte多步骤表单中
svelte:component的TS类型错误 你的问题根源是给steps定义的类型太宽泛——typeof SvelteComponentDev是所有Svelte组件的基础类型,它的属性定义里不包含你自定义的store必填项,所以TypeScript会认为你没给组件传必要的store参数,哪怕你已经在svelte:component里传递了。
给你两种可行的解决办法:
方法一:定义专属的步骤组件类型
先声明一个约束所有步骤组件的类型,明确要求组件必须接受store属性:
import type { SvelteComponentDev } from 'svelte/internal'; // 定义所有步骤组件必须满足的类型 type StepComponent = typeof SvelteComponentDev & { $$prop_def: { store: StepFlowStore }; }; // 用这个类型约束steps const steps: Record<FormSteps, StepComponent> = { [mySteps.first]: AddressForm, [mySteps.second]: DetailsForm, [mySteps.third]: FinalForm };
这样TypeScript就能识别到每个组件都需要store,且你已经在svelte:component中传递了该属性,错误就会消失。
方法二:让TypeScript自动推断类型
直接去掉steps的显式类型声明,让TS根据你赋值的组件自动推断类型:
const steps = { [mySteps.first]: AddressForm, [mySteps.second]: DetailsForm, [mySteps.third]: FinalForm };
这种方式下,TS会自动识别到每个组件都有store这个必填属性,结合你在svelte:component里传递的{store},就不会再报错。
本质上这不是svelte:component的固有问题,只是TypeScript需要明确知道组件的属性要求,避免类型不匹配的风险。
内容的提问来源于stack exchange,提问作者dinocode
相关产品推荐
相关产品推荐

