2

I'm working on a new Svelte project using Typescript. I'm also using the svelte-mui component module which was not written in Typescript and does not have a types file. Whenever I try to use a component, VSCode highlights the component with annoying red squiggles because Typescript doesn't know about the svelte properties that are a part of the object. The project builds and runs fine, but I would like to figure out how to tell Typescript what type they are. I know all the components extend SvelteComponent but I don't know how to tell Typescript that.

<script>
import Button from 'svelte-mui';
</script>

<Button on:click={() => {console.log('Clicked')}}>My Button</Button>

The last line will be highlighted as an error in the editor.

How do I tell Typescript that Button extends SvelteComponent?

Edit: @tmdesigned

I followed the instructions in the link provided by tmdesigned below, but no dice. I'm new to Typescript so maybe I'm still doing something wrong. I ended up with a file located at

types\svelte-mui\index.d.ts

that contains

declare module 'svelte-mui' {
    import { SvelteComponent } from "svelte/internal";

    class Button extends SvelteComponent{}

    export { Button }
}

but the error still persists.

3
  • I should probably add that I can import SvelteComponent with import { SvelteComponent } from 'svelte/internal'; Commented Jul 31, 2020 at 15:03
  • detroitlabs.com/blog/2018/02/28/… Commented Jul 31, 2020 at 16:22
  • @tmdesigned Thanks for the link, but the error still persists. See the edit above. Commented Aug 1, 2020 at 6:11

1 Answer 1

1

I hit similar errors using Svelte Material UI, but the solution should translate to svelte-mui.

First, configure typeRoots in tsconfig.json so that the compiler finds your declaration file in the types directory:

{
  "compilerOptions": {
     ...
    "typeRoots": [
      "./node_modules/@types",
      "./types"
    ]
  }
}

Make sure not to add "types" to the exclude list as suggested by the linked page that you mentioned. I think that would prevent the compiler from using your declaration file.

Then, update types/svelte-mui/index.d.ts to:

declare module 'svelte-mui' {
  import type { SvelteComponent } from "svelte";

  class Button extends SvelteComponent { }
  export default Button;
}

Restart VSCode or run the "Svelte: Restart Language Server" command to ensure that it uses the new configuration. Your Button component should no longer show an error.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.