export typescript type in svelte file
Asked Answered
K

2

23

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.

Kathlenekathlin answered 25/9, 2020 at 12:48 Comment(4)
I guess it's just an issue with the linter. When you run the TypeScript check does it work?Henceforth
yep, it will run with no error. I use sapper but the importing type will also show me an error and autocomplete not working.Kathlenekathlin
TypeScript support in svelte is really new so I guess it's just an issue with the linter that you are using (and not the TypeScript compiler used by svelte). Which linter are you using?Henceforth
I didn't set any linter and I guess it's sapper default linterKathlenekathlin
M
36

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:

<script context="module" lang="ts">
  export type myNewType = {name: string};
</script>

<script>
  export let aProp: string;
</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.

Monjan answered 25/9, 2020 at 14:32 Comment(1)
This works but doesn't support Svelte's native export let data: under different context it becomes unavailable, so I can't for example export type MyDataType = data , because it's comming from different script tag :(Lictor
D
7

Just in case it helps anyone, I was having an issue importing my own type which I had declared in a .ts file, into another library file:

My type was declared as follows:

export type UserAuth = {
    name: string,
    email: string,
    token: ''
};

An in my /lib/auth.ts file, I was attempting to import it as follows:

import { UserAuth } from "../types/user.auth";

Which produced an error that the type has not been exported.

The following fixed the issue for me:

import type { UserAuth } from "../types/user.auth";
Declared answered 31/12, 2021 at 19:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.