0% found this document useful (0 votes)
86 views

Svelte Custom Stores TypeScript Declaration - by David Dal Busco - Better Programming

The document discusses how to declare the types of custom stores in TypeScript for a Svelte application. It demonstrates creating a custom store that exposes functions like incrementing and resetting values, while hiding the internal store data. It shows inheriting from the Readable type and defining a new interface to describe the store's type, improving type safety and allowing TypeScript to correctly infer the store's types. This allows tooling like WebStorm to understand the store's usage in TS code.

Uploaded by

howesteve
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

Svelte Custom Stores TypeScript Declaration - by David Dal Busco - Better Programming

The document discusses how to declare the types of custom stores in TypeScript for a Svelte application. It demonstrates creating a custom store that exposes functions like incrementing and resetting values, while hiding the internal store data. It shows inheriting from the Readable type and defining a new interface to describe the store's type, improving type safety and allowing TypeScript to correctly infer the store's types. This allows tooling like WebStorm to understand the store's usage in TS code.

Uploaded by

howesteve
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

5/22/23, 10:37 PM Svelte Custom Stores TypeScript Declaration | by David Dal Busco | Better Programming

This is your last free member-only story this month. Upgrade for unlimited access.

Member-only story

Svelte Custom Stores TypeScript Declaration


How to declare the types of custom stores?

David Dal Busco · Follow


Published in Better Programming
4 min read · Jan 20

Listen Share More

​Svelte offers some nice easy-to-use store concepts. One of those is “custom stores”
which makes handy the obfuscation of the reactive stored data and its access
through a set of custom-defined functions.
https://betterprogramming.pub/svelte-custom-stores-typescript-declaration-db34c0f7e7b8 1/14
5/22/23, 10:37 PM Svelte Custom Stores TypeScript Declaration | by David Dal Busco | Better Programming

For example, a counter that counts apples and bananas, I can create a custom store
that does not expose directly my data. Within a function, I can “hide” the store and
expose only the functions I want to use in my apps instead of exposing publicly set ​

and ​update ​. This to avoid misbehavior and unexpected changes, what can be really
useful as the code base grows.

import { writable } from 'svelte/store';

export interface Counter {


apples: number;
bananas: number;
}

const initStore = () => {


const initialCounter: Counter = {
apples: 0,
bananas: 0
};

const { subscribe, set, update } =


writable(initialCounter);

return {
subscribe,
incBanana: () =>
update(({ bananas, ...rest }) => ({
...rest,
bananas: bananas + 1
})),
decBanana: () =>
update(({ bananas, ...rest }) => ({
...rest,
bananas: bananas - 1
})),
reset: () => set(initialCounter)
Open in app
};
};

export const counter = initStore();

Above code, snippet follows Svelte’s documentation example with the addition of a
type — Counter ​— for the object saved in my store and few custom functions — ​
incBanana ​, ​decBanana ​and ​reset ​.

https://betterprogramming.pub/svelte-custom-stores-typescript-declaration-db34c0f7e7b8 2/14
5/22/23, 10:37 PM Svelte Custom Stores TypeScript Declaration | by David Dal Busco | Better Programming

Note that I just did not implement the “apples” related functions to keep the snippet small.
In a real use case I might have even extracted the ​update() ​part to a function to avoid
double code but, I also skipped this part because it would have not much value in this blog
post context.

​When binding in a component, it works as expected.

However, even if npm run dev|build|check are all fine, Webstorm is not being able to
derive the store values when used in a TypeScript script ​block.

https://betterprogramming.pub/svelte-custom-stores-typescript-declaration-db34c0f7e7b8 3/14
5/22/23, 10:37 PM Svelte Custom Stores TypeScript Declaration | by David Dal Busco | Better Programming

​I do not know exactly if it is yet another issue of the Jetbrains Svelte plugin or if the
store is derived as any ​type by the bundler (which would ignore the strict ​option).

Nevertheless, I rather like to fix the issue by improving the type of declaration of
the store.

Because my custom store exposes my homemade functions but, also the root ​
subscribe ​feature, its declaration has to provide support for it as well.

​Therefore the easiest way in my opinion is to inherit the existing ​Readable ​type of
Svelte.

import {type Readable} from 'svelte/store';

export interface AuthStore extends Readable<Counter> {


incBanana: () => void;
decBanana: () => void;
reset: () => void;
}

By setting the generic types to my custom data type — ​Counter — I can instruct
which type is handled in the store and by declaring my functions, I can improve the

https://betterprogramming.pub/svelte-custom-stores-typescript-declaration-db34c0f7e7b8 4/14
5/22/23, 10:37 PM Svelte Custom Stores TypeScript Declaration | by David Dal Busco | Better Programming

typings.

I can use this new interface to set the return type of the initialization function — ​
initStore — and that’s already it.

import { type Readable, writable } from 'svelte/store';

export interface Counter {


apples: number;
bananas: number;
}

export interface AuthStore extends Readable<Counter> {


incBanana: () => void;
decBanana: () => void;
reset: () => void;
}

const initStore = (): AuthStore => {


const initialCounter: Counter = {
apples: 0,
bananas: 0
};

const { subscribe, set, update } =


writable(initialCounter);

return {
subscribe,
incBanana: () =>
update(({ bananas, ...rest }) => ({
...rest,
bananas: bananas + 1
})),
decBanana: () =>
update(({ bananas, ...rest }) => ({
...rest,
bananas: bananas - 1
})),
reset: () => set(initialCounter)
};
};

export const counter = initStore();

When I open my component, I notice that Webstorm now understands correctly the
type of my data.
https://betterprogramming.pub/svelte-custom-stores-typescript-declaration-db34c0f7e7b8 5/14
5/22/23, 10:37 PM Svelte Custom Stores TypeScript Declaration | by David Dal Busco | Better Programming

​To infinity and beyond


David

​For more adventures, follow me on Twitter.

Programming Web Development Svelte Typescript JavaScript

Follow

Written by David Dal Busco


1K Followers · Writer for Better Programming
https://betterprogramming.pub/svelte-custom-stores-typescript-declaration-db34c0f7e7b8 6/14
5/22/23, 10:37 PM Svelte Custom Stores TypeScript Declaration | by David Dal Busco | Better Programming

Freelancer by day | Creator of Juno.build by night

More from David Dal Busco and Better Programming

David Dal Busco in Better Programming

Translate (i18n) a Svelte app without external dependencies


Adding internationalization support to a Svelte application: a step-by-step guide.

· 9 min read · 3 days ago

52 2

https://betterprogramming.pub/svelte-custom-stores-typescript-declaration-db34c0f7e7b8 7/14
5/22/23, 10:37 PM Svelte Custom Stores TypeScript Declaration | by David Dal Busco | Better Programming

Timothy Mugayi in Better Programming

How To Build Your Own Custom ChatGPT With Custom Knowledge Base
Feed your ChatGPT bot with custom data sources

· 11 min read · Apr 7

4K 93

Emily Dresner in Better Programming

Why an Engineering Manager Should Not Review Code


https://betterprogramming.pub/svelte-custom-stores-typescript-declaration-db34c0f7e7b8 8/14
5/22/23, 10:37 PM Svelte Custom Stores TypeScript Declaration | by David Dal Busco | Better Programming

When discussing team organization, I am often asked: “Why don’t you have the tech lead
manage the team?” My response is to hiss like a…

8 min read · May 11

1.4K 20

David Dal Busco in Better Programming

How to Create a Modal For Your Angular App Without Using a Library
Modals without dependencies

· 3 min read · Mar 30, 2020

178 2

See all from David Dal Busco

See all from Better Programming

https://betterprogramming.pub/svelte-custom-stores-typescript-declaration-db34c0f7e7b8 9/14
5/22/23, 10:37 PM Svelte Custom Stores TypeScript Declaration | by David Dal Busco | Better Programming

Recommended from Medium

Ecky Putrady in Better Programming

How to Interact With PostgreSQL From Rust Using SQLx


The important things you need to know to get the job done.

· 4 min read · Jan 23

61 2

https://betterprogramming.pub/svelte-custom-stores-typescript-declaration-db34c0f7e7b8 10/14
5/22/23, 10:37 PM Svelte Custom Stores TypeScript Declaration | by David Dal Busco | Better Programming

Shinichi Okada in mkdir Awesome

How to Create Svelte Component Libraries with SvelteKit 1.5


Step-by-Step Instructions for Creating and Publishing Svelte Component Libraries

· 4 min read · Feb 14

1 1

Lists

Stories to Help You Grow as a Software Developer


19 stories · 45 saves

Leadership
30 stories · 16 saves

How to Run More Meaningful 1:1 Meetings


11 stories · 20 saves

Stories to Help You Level-Up at Work


19 stories · 36 saves

https://betterprogramming.pub/svelte-custom-stores-typescript-declaration-db34c0f7e7b8 11/14
5/22/23, 10:37 PM Svelte Custom Stores TypeScript Declaration | by David Dal Busco | Better Programming

David Li

How to transcribe youtube videos using whispers


· 3 min read · Feb 2

17

Timothy Mugayi in Better Programming

How To Build Your Own Custom ChatGPT With Custom Knowledge Base
Feed your ChatGPT bot with custom data sources

https://betterprogramming.pub/svelte-custom-stores-typescript-declaration-db34c0f7e7b8 12/14
5/22/23, 10:37 PM Svelte Custom Stores TypeScript Declaration | by David Dal Busco | Better Programming

· 11 min read · Apr 7

4K 93

Leonie Monigatti in Towards Data Science

Getting Started with LangChain: A Beginner’s Guide to Building LLM-


Powered Applications
A LangChain tutorial to build anything with large language models in Python

· 12 min read · Apr 25

1.6K 13

https://betterprogramming.pub/svelte-custom-stores-typescript-declaration-db34c0f7e7b8 13/14
5/22/23, 10:37 PM Svelte Custom Stores TypeScript Declaration | by David Dal Busco | Better Programming

Teemu Maatta in Better Programming

OpenAI’s Embedding Model With Vector Database


The updated Embedding model offers State-of-the-Art performance with 4x longer context
window. Thew new model is 90% cheaper. The smaller…

· 12 min read · Jan 10

263 7

See more recommendations

https://betterprogramming.pub/svelte-custom-stores-typescript-declaration-db34c0f7e7b8 14/14

You might also like