How to import/export Typescript type/interface in Svelte file using Sapper?

13.5k Views Asked by At

What I'm trying to achieve

I'm trying to create a svelte component (using TypeScript), create a type, export it and import it into another file.

  • Options.svelte => svelte component that also exports type
  • index.svelte => import component and use type

What I have

I have a component, for example:

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}

And I use that component in another file, for example:

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 />

What I get

This continues to give me the following error when running 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)

Question

How might I export/import the TypeScript type/interface from the svelte component to the index.svelte file so that I may use it?

I followed what is written in this answer, but cannot figure out how to import it without constant errors. Is this an issue with svelte-check?


Update 1

I can confirm that this issue is specific to svelte-check (current version 1.1.17).

I can run sapper dev and there are no errors.


Update 2

As mentioned by dummdidumm in their answer, the first error is result of a typo, I should instead have the following import (I was importing it as default - which is the component itself, not the type):

import type { Option } from './Options.svelte'

The other errors still persist whenever I pass an attribute to a custom component built with TypeScript.

2

There are 2 best solutions below

1
On

The error is misleading. You import the type as a default import. The default import is the component. You should write import type { Option } from './Options.svelte' instead.

0
On

I had properly imported the type as specified by dummdidumm.

For me, simply restarting my project (npm run dev for me) fixed the issue.