109 lines
2.5 KiB
Markdown
109 lines
2.5 KiB
Markdown
# 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:
|
|
|
|
```javascript
|
|
// ❌ 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
|
|
|
|
```javascript
|
|
// 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
|
|
|
|
```javascript
|
|
// 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:
|
|
|
|
1. Create a `.d.ts` file for your store:
|
|
|
|
```typescript
|
|
// 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 };
|
|
```
|
|
|
|
2. Add `<script lang="ts">` to your Svelte components to enable TypeScript.
|
|
|
|
## Best Practices
|
|
|
|
1. Keep all state updates within the `update` callback
|
|
2. Return a new state object, don't mutate the existing one
|
|
3. Use the spread operator (`...`) to preserve existing properties
|
|
4. For complex updates, break down the logic into smaller helper functions |