【发布时间】:2020-11-27 20:15:08
【问题描述】:
我正在努力实现的目标
我正在尝试创建一个苗条的组件(使用 TypeScript),创建一个类型,将其导出并导入到另一个文件中。
-
Options.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)
问题
如何将 TypeScript 类型/接口从 svelte 组件导出/导入到 index.svelte 文件以便我可以使用它?
我按照this answer 中的内容进行操作,但无法弄清楚如何导入它而不会出现持续错误。这是svelte-check 的问题吗?
更新 1
我可以确认此问题特定于 svelte-check(当前版本 1.1.17)。
我可以运行sapper dev 并且没有错误。
更新 2
正如dummdidumm in their answer 所提到的,第一个错误是拼写错误的结果,我应该使用以下导入(我将其作为默认导入 - 这是组件本身,而不是类型):
import type { Option } from './Options.svelte'
每当我将属性传递给使用 TypeScript 构建的自定义组件时,其他错误仍然存在。
【问题讨论】:
-
第二个错误说明了
SwitchMulti,但我在代码中没有看到这样的组件用法。SwitchMulti是什么?它来自哪里?
标签: typescript svelte sapper