You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 04:22:41