Typing svelte $store variable
Asked Answered
Z

1

11

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

Zolnay answered 13/1, 2021 at 14:10 Comment(0)
S
13

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.

Splasher answered 13/1, 2021 at 14:40 Comment(5)
Just in case, this does not work in while using Vite for a Svelte project.Excision
Is ther guidance on how to do this using vite?Bottleneck
Although it is an old question, I think there is something wrong! Why do you import writable twice? Please correct me if I'm wrong.Emblematize
@MBParvezRony 10x for the correction.Splasher
This really does not answer the question if you're not using Typescript. :(Jasso

© 2022 - 2024 — McMap. All rights reserved.