2.5 KiB
2.5 KiB
Svelte Store Patterns for TypeScript
This document outlines the best practices for working with Svelte stores in a TypeScript environment.
Common TypeScript Errors
When working with Svelte stores in TypeScript, you might encounter errors like:
Property 'customMethod' does not exist on type 'Writable<MyStore>'.
These happen because TypeScript doesn't recognize custom methods added to Svelte stores.
Solution 1: Use the Update Method Pattern
Instead of creating custom methods on stores, use the standard update method that comes with every Svelte writable store:
// ❌ Don't do this - TypeScript will complain
myStore.customMethod(value);
// ✅ Do this instead - TypeScript friendly
myStore.update(state => {
// Update the state here
return updatedState;
});
Example: Adding a Participant
// Instead of:
expenseStore.addParticipant();
// Use:
expenseStore.update(store => {
const newParticipant = {
id: generateId(),
name: '',
address: '',
amount: '0'
};
return {
...store,
currentExpense: {
...store.currentExpense,
participants: [...store.currentExpense.participants, newParticipant]
}
};
});
Example: Updating a Participant
// Instead of:
expenseStore.updateParticipant(id, { name: 'New Name' });
// Use:
expenseStore.update(store => {
const updatedParticipants = store.currentExpense.participants.map(p =>
p.id === id ? { ...p, name: 'New Name' } : p
);
return {
...store,
currentExpense: {
...store.currentExpense,
participants: updatedParticipants
}
};
});
Solution 2: Type Declarations (For More Complex Apps)
For larger applications, you might want to create proper TypeScript declarations for your stores:
- Create a
.d.tsfile for your store:
// expenseStore.d.ts
import { Writable } from 'svelte/store';
interface ExpenseStoreState {
currentExpense: Expense;
// other properties...
}
interface ExpenseStore extends Writable<ExpenseStoreState> {
addParticipant: () => void;
removeParticipant: (id: string) => void;
// other custom methods...
}
declare const expenseStore: ExpenseStore;
export { expenseStore };
- Add
<script lang="ts">to your Svelte components to enable TypeScript.
Best Practices
- Keep all state updates within the
updatecallback - Return a new state object, don't mutate the existing one
- Use the spread operator (
...) to preserve existing properties - For complex updates, break down the logic into smaller helper functions