我的目标
我试图创建一个使用TypeScript编写的Svelte组件,创建一种类型,将其导出并在另一个文件中进行导入。
Options.svelte
=> Svelte组件同时导出类型index.svelte
=> 导入组件并使用类型
我的现状
我已经有一个组件,例如:
Options.svelte
<script lang="ts" context="module">
export type Option = {
label: string
};
</script>
<script lang="ts">
export let options: Option[]
</script>
{#each options as option}
<div>{option.label}</div>
{/each}
我在另一个文件中使用了该组件,例如:
index.svelte
<script lang="ts">
import Options from './Options.svelte'
import type Option from './Options.svelte'
let options: Option[] = [{ label: 'one' }, { label: 'two' }]
</script>
<Options bind:options />
我得到了什么
当我运行 svelte-check --ignore src/node_modules/@sapper
时,仍然会出现以下错误:
Error: Type '{ label: string; }' is missing the following properties from type 'SvelteComponentDev': $set, $on, $destroy, $capture_state, and 2 more. (ts)
Error: JSX element class does not support attributes because it does not have a '$$prop_def' property. (ts)
Error: Type definitions are missing for this Svelte Component. It needs a class definition with at least the property '$$prop_def' which should contain a map of input property definitions.
Example:
class ComponentName { $$prop_def: { propertyName: string; } }
'SwitchMulti' cannot be used as a JSX component.
Its instance type 'SvelteComponentDev' is not a valid JSX element.
Property '$$prop_def' is missing in type 'SvelteComponentDev' but required in type 'ElementClass'. (ts)
问题
如何将 Svelte 组件中的 TypeScript 类型/接口导出/导入到 index.svelte
文件中,以便我可以使用它?
我按照这个答案所写的做法进行尝试,但无法解决不断出现的错误。这是 svelte-check
的问题吗?
更新 1
我确定这个问题只出现在 svelte-check
(当前版本 1.1.17)
) 中。
我可以运行 sapper dev
而不会出现错误。
更新 2
正如dummdidumm 在他们的回答中所提到的,第一个错误是由于拼写错误造成的。我应该使用以下导入语句(我之前误将其作为默认导出 - 这是组件本身,而不是类型):
import type { Option } from './Options.svelte'
无论我何时将属性传递给使用TypeScript构建的自定义组件,其他错误仍然存在。
SwitchMulti
,但是我在代码中没有看到这种组件的使用。SwitchMulti
是什么,它从哪里来? - dummdidumm