typescriptsveltesapper

export typescript type in svelte file


I want to export the type that I defined in one of my files and import it inside another file.

export type myNewType = {name: string};

linter show me bellow error when I add export:

Modifiers cannot appear here.

I can make it work by creating a new ts file and import the type from it. I just want to know if there is a way to define type inside svelte file or not.

Update:

I use the sapper template and it will run without error but TS functionality not work and show me errors in vscode when importing type and export type from svelte file.


Solution

  • You need export the type from a module-script, not the normal script. You also need to add the lang="ts" attribute on either the normal script or the module-script. This will work:

    Svelte 3 and 4:

    <script context="module" lang="ts">
      export type myNewType = {name: string};
    </script>
    
    <script>
      export let aProp: string;
    </script>
    
    <p>some html</p>
    

    Svelte 5+:

    <script module lang="ts">
      export type myNewType = {name: string};
    </script>
    
    <script>
      let { aProp }: { aProp: string } = $props();
    </script>
    
    <p>some html</p>
    

    In general, whenever you want to import something from another Svelte file which is not the component itself, you need to declare that export inside the module-script.