ivanhofer / sveltekit-typescript-showcase

This repository shows how Svelte and SvelteKit work together with TypeScript.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

example about how to type functions exported from svelte components

opensas opened this issue · comments

provide an example an explanation about how to type an exported function

Something like this example from @tanhauhau

<script>
	let isOpen = true;
	let name = '';
	let email = '';
	
	export function openModal() {
		isOpen = true;
	}
	[...]
}

Right now, with ts, I get a Property 'openModal' does not exist on type 'default'.ts(2339)

you need to tell TypeScript what type the component binding (let dialog: Dialog) should have:

App.svelte

<script lang="ts">
   import Dialog from './Dialog.svelte'
   let dialog: Dialog
</script>

<Dialog bind:this={dialog} />

<button on:click={() => dialog.openModal() }>Open dialog</button>

Dialog.svelte

<script lang="ts">
   let isOpen = true;

   export function openModal() {
      isOpen = true;
   }
</script>

<!-- markup -->