Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typing svelte $store variable

I wanted to know if it is possible de type the dollar sign value of a custom svelte store ?

From this example :

app.svelte

<script>
    import { count } from './stores.js';
</script>

<h1>The count is {$count}</h1>

<button on:click={count.increment}>+</button>
<button on:click={count.decrement}>-</button>
<button on:click={count.reset}>reset</button>

stores.js

import { writable } from 'svelte/store';

function createCount() {
    const { subscribe, set, update } = writable(0);

    return {
        subscribe,
        increment: () => {},
        decrement: () => {},
        reset: () => {}
    };
}

export const count = createCount();

How do you type the variable {$count} with your own typescript interface ?

Thank you for your help

like image 292
Tryall Avatar asked Apr 01 '26 19:04

Tryall


1 Answers

You can rename your stores.js to stores.ts and add a type, like:

import { Writable, writable } from "svelte/store"

type CountStore = {
  subscribe: Writable<number>["subscribe"]
    
  increment: () => void
  decrement: () => void
  reset: () => void
}

function createCount(): CountStore {
.
.
.

EDIT:

You don't need to define the type, Typescript does it great, so you can just rename the original file from js to ts.

like image 88
CD.. Avatar answered Apr 03 '26 15:04

CD..