使用TypeScript+SvelteKit如何传递Svelte组件属性并定义类型
解决Svelte组件中传入子组件的TypeScript类型定义问题
要给PrimaryButton.svelte中的icon prop定义正确的TypeScript类型,直接使用Svelte官方提供的ComponentType类型即可:
基础用法(无props约束)
在组件中导入ComponentType,将icon定义为可选的组件类型:
<script lang="ts"> import type { ComponentType } from 'svelte'; // icon为可选组件,默认值设为undefined export let icon: ComponentType | undefined = undefined; </script> <button> {#if icon} <svelte:component this={icon} /> {/if} <slot /> </button>
带Props约束的用法
如果图标组件需要接收特定props(比如size、color),可以先定义props接口,再通过ComponentType<Props>约束组件类型:
<script lang="ts"> import type { ComponentType } from 'svelte'; // 定义图标组件的props类型 interface IconProps { size?: number; color?: string; } // 限制icon只能接受符合IconProps的组件 export let icon: ComponentType<IconProps> | undefined = undefined; </script> <button> {#if icon} <!-- 给图标组件传入props --> <svelte:component this={icon} size={24} color="currentColor" /> {/if} <slot /> </button>
说明
ComponentType是Svelte内置的类型,专门用来表示组件的构造函数,完全匹配<svelte:component>的this属性要求。这样定义后,TypeScript会正确校验传入的组件是否符合类型要求,同时支持组件的props类型检查。
内容的提问来源于stack exchange,提问作者user1354934
相关产品推荐
相关产品推荐

