Type-safe storage library for TypeScript
- 🎯 Full Type Safety - Guaranteed key and value types in TypeScript
- 🎯 Simple API - Intuitive and easy-to-use interface
- 🏷️ Namespace Support - Key management with prefix
- ⚙️ Custom Serialization - Support for serialization beyond JSON
- 🪶 Lightweight - Pure TypeScript implementation with no dependencies
# npm
npm install @yeunoia/typed-storage
# yarn
yarn add @yeunoia/typed-storage
# pnpm
pnpm add @yeunoia/typed-storageimport { typedLocalStorage } from '@yeunoia/typed-storage'
// Define types
type User = { id: number; name: string }
type Settings = { theme: 'light' | 'dark'; lang: string }
// Create storage instances
const userStorage = typedLocalStorage<'user', User>()
const settingsStorage = typedLocalStorage<'settings', Settings>({
options: { prefix: 'app' },
})
// Store and retrieve data
userStorage.set('user', { id: 1, name: 'John' })
const user = userStorage.get('user') // User | null
settingsStorage.set('settings', { theme: 'dark', lang: 'en' })
const settings = settingsStorage.get('settings') // Settings | nullimport { typedSessionStorage } from '@yeunoia/typed-storage'
// Use session storage
const sessionStorage = typedSessionStorage<'temp', string>({
options: { prefix: 'session' },
})
sessionStorage.set('temp', 'temporary data')
const temp = sessionStorage.get('temp') // string | null// Custom serialization
const customStorage = typedLocalStorage<'data', any>({
options: {
prefix: 'custom',
serializer: {
serialize: (value) => btoa(JSON.stringify(value)),
deserialize: (value) => JSON.parse(atob(value)),
},
},
})Generic Types:
K: Storage key type (extends string)V: Storage value type
Configuration Options:
prefix: Prefix to add to keysserializer: Custom serialization/deserialization functions
Methods:
get(key): V | null- Get valueset(key, value): void- Set valueremove(key): void- Remove keyclear(): void- Clear all datakeys(): K[]- Get all keyssize(): number- Get number of stored items
MIT © yeunoia