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

如何在Svelte中让数组强类型匹配组件导出属性(无需自定义类型)

在Svelte(TypeScript)中自动匹配组件属性类型约束数组元素

完全可以实现,不用手动维护单独的属性类型,直接利用Svelte内置的ComponentProps工具类型就能让TypeScript自动推导组件的导出属性,进而约束数组元素的类型,检测拼写错误。

实现步骤

  1. 导入Svelte的ComponentProps类型
  2. 用ComponentProps<typeof Thing>获取Thing组件的属性类型,再用它约束数组类型

修改后的+Page.svelte代码如下:

<script lang="ts">
  // +Page.svelte
  import Thing from '$lib/Thing.svelte';
  import type { ComponentProps } from 'svelte';

  // 用ComponentProps自动获取Thing的属性类型,约束数组元素
  const things: Array<ComponentProps<typeof Thing>> = [{
    name: "Bob", // 拼写正确才不会报错
    age: 36  
  }];
</script>

{#each things as thing}
  <Thing {...thing} />
{/each}

效果说明

  • 如果你像示例里那样把name写成naem,TypeScript和IntelliSense会立刻报错,提示该对象缺少name属性,且存在未定义的naem属性
  • 当Thing.svelte里的导出属性(比如新增/修改export let的字段)发生变化时,数组的类型会自动同步,完全不用手动更新类型定义

这个方案在SvelteKit和普通Svelte+TypeScript项目中都能直接使用,不需要额外依赖。

内容的提问来源于stack exchange,提问作者CT14.IT

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 06:12:17