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

SvelteKit组件Props类型报错:无法赋值给never类型

解决SvelteKit + TypeScript中组件Props出现Type '<类型>' is not assignable to type 'never'错误

错误成因

你在组件中错误地将组件Props定义放在了带有context="module"的<script>标签内:

  • context="module"标记的脚本属于模块级代码,仅在组件首次加载时执行一次,其中的export let是导出模块变量,而非组件的响应式Props。
  • TypeScript无法识别模块级导出为组件Props,因此会将父组件传递的Props类型推断为never,最终触发Type '<某props类型>' is not assignable to type 'never'的类型不匹配错误。

解决方法

将组件的Props定义移到不带context="module"的普通<script lang="ts">标签中,类型接口可以保留在模块级脚本里(或移到普通脚本,不影响类型导出)。

修改后的组件代码

src/lib/components/Navbar.svelte

<script context="module" lang="ts">
import MdMenu from 'svelte-icons/md/MdMenu.svelte';

// 类型接口保留在模块级脚本,用于导出给父组件使用
export interface NavItem {
    text: string;
    link: string;
};
</script>

<script lang="ts">
// 组件Props移到普通脚本,Svelte会识别为响应式Props
export let items: NavItem[] = [{
    text: "Example",
    link: "https://www.example.com/"
}];
</script>

<div class="absolute flex transition-transform ease-in-out duration-300 translate-x-0 hover:-translate-x-0 bg-slate-500 transition-colors text-white">
    <div class="p-1">
        <div class="w-6 h-6">
            <MdMenu/>
        </div>
    </div>

    {#each items as item}
        <div class="p-1 hover:text-orange-500 hover:bg-slate-200">
            <a href="{item.link}"> {item.text} </a>
        </div>
    {/each}
</div>

src/lib/components/Linkage.svelte

<script context="module" lang="ts">
export interface Link {
    icon: null | string | unknown;
}
</script>

<script lang="ts">
// 组件Props移到普通脚本
export let links: Link[] = [];
</script>

验证修改

修改完成后,运行npx svelte-check,原有的类型错误会消失,父组件传递的Props也能被正确识别类型。

内容的提问来源于stack exchange,提问作者Tobiky

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 11:42:32