A small, focused TypeScript library for safer code through functional patterns using natural language. Inspired by folktale.
folklore
Folklore provides two essential types for writing more reliable TypeScript: Optional for handling
optional values and Result for managing errors without exceptions.
Installation
JSR (recommended for Deno/modern setups):
# Deno
deno add jsr:@folklore/folklore
# npm (via JSR)
npx jsr add @folklore/folklorenpm:
npm install folkloreQuick Start
Optional - Safe Optional Values
Handle nullable values with readable, natural syntax:
import { Optional } from 'folklore'
function findUser(id: string): Optional<User> {
const user = database.get(id)
return Optional.FromNullable(user)
}
// Basic transformation and fallback
const greeting = findUser('123')
.transform((user) => user.name)
.transform((name) => `Hello, ${name}!`)
.otherwise('Hello, stranger!')
// Optional chaining with multiple fallbacks
const displayName = primaryCache
.retrieve(key)
.optionally(backupCache.retrieve(key))
.otherwise('Guest')
// Side effects with when
findUser('123').when({
some: (user) => analytics.track(user.id),
none: () => analytics.trackAnonymous(),
})
// Filtering with where
const validId = getUserId()
.where((id) => id > 0)
.transform((id) => fetchUser(id))
.otherwise(guestUser)Result - Error Handling Without Exceptions
Manage errors explicitly in your type system:
import { Result } from 'folklore'
function parseConfig(json: string): Result<Config> {
return Result.Try(() => JSON.parse(json))
.chain((data) => validateConfig(data))
}
const config = parseConfig(input)
.matchWith({
Ok: (cfg) => console.log('Loaded config:', cfg),
Error: (err) => console.error('Failed to load config:', err),
})
// Or with async operations
const response = await Result.FromPromise(fetch('/api/data'))
.then((result) => result.map((res) => res.json()))API
The library includes comprehensive JSDoc documentation - your editor’s IntelliSense will show you examples and usage guidance for every method. See #13: A Retelling, not a reimplementation for more details on API decisions.
Status & Contributing
Folklore is used in production on several large/critical TypeScript projects and is well-tested.
If you’re interested in contributing, please open an issue to discuss your idea first. I am very open to anything docs/stability/project related.
License
folklore is provided under the Mozilla Public License 2.0.
A copy of the MPLv2 is included license.md file for convenience.