如何使用 Sapper 在 Svelte 文件中导入/导出 Typescript 类型/接口?

ctw*_*els 6 typescript svelte sapper

我正在努力实现的目标

我正在尝试创建一个 svelte 组件(使用 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}
Run Code Online (Sandbox Code Playgroud)

我在另一个文件中使用该组件,例如:

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 />
Run Code Online (Sandbox Code Playgroud)

我得到的

这在运行时继续给我以下错误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)
Run Code Online (Sandbox Code Playgroud)

我如何将 TypeScript 类型/接口从 svelte 组件导出/导入到index.svelte文件中以便我可以使用它?

我遵循了这个答案中写的内容,但无法弄清楚如何在没有持续错误的情况下导入它。这是一个问题svelte-check吗?


更新 1

我可以确认此问题特定于svelte-check(当前版本1.1.17).

我可以运行sapper dev并且没有错误。


更新 2

正如dummdidumm 在他们的回答中提到的,第一个错误是拼写错误的结果,我应该使用以下导入(我将它作为默认导入 - 这是组件本身,而不是类型):

import type { Option } from './Options.svelte'
Run Code Online (Sandbox Code Playgroud)

每当我将属性传递给使用 TypeScript 构建的自定义组件时,其他错误仍然存​​在。

dum*_*umm 8

该错误具有误导性。您可以将类型作为默认导入进行导入。默认导入的是组件。你应该写import type { Option } from './Options.svelte'