I'm following the tutorial provided by the Svelte team in their website! There is this section in the tutorial that basically explains how we can expose certain functionalities from a custom component: Tutorial Page
I get the concept but when i'm trying to implement it with typescript i get no type safety out of the box!
Example:
<!-- text.svelte -->
<script lang="ts">
let content = $state('Hello');
export function getContent() {
return content;
}
</script>
<p>{content}</p>
<!-- app.svelte -->
<script lang="ts">
import Text from './text.svelte';
let text;
$effect(() => {
console.log(text.getContent());
});
</script>
<Text bind:this={text} />
in the example, type of the text variable is any!
also typing the variable like this does not give me access to getContent
method:
let text: Text;
Edit: Since PR 2553 additional changes may no longer be necessary.
In Svelte 5 components are functions and you can get the type of an instance via their ReturnType
:
let text: ReturnType<typeof Text>;