This skill helps you migrate imperative TypeScript code to fp-ts patterns, enabling explicit errors, safe optional handling, and functional composition.
npx playbooks add skill whatiskadudoing/fp-ts-skills --skill fp-refactor
This skill provides comprehensive patterns and strategies for migrating existing imperative TypeScript code to fp-ts functional programming patterns.
---
Traditional try-catch blocks have several issues:
function parseJSON(input: string): unknown {
try {
return JSON.parse(input);
} catch (error) {
throw new Error(`Invalid JSON: ${error}`);
}
}
function validateUser(data: unknown): User {
try {
if (!data || typeof data !== 'object') {
throw new Error('Data must be an object');
}
const obj = data as Record<string, unknown>;
if (typeof obj.name !== 'string') {
throw new Error('Name is required');
}
if (typeof obj.age !== 'number') {
throw new Error('Age must be a number');
}
return { name: obj.name, age: obj.age };
} catch (error) {
throw error;
}
}
// Usage with nested try-catch
function processUserInput(input: string): User | null {
try {
const data = parseJSON(input);
const user = validateUser(data);
return user;
} catch (error) {
console.error('Failed to process user:', error);
return null;
}
}
import * as E from 'fp-ts/Either';
import * as J from 'fp-ts/Json';
import { pipe } from 'fp-ts/function';
interface User {
name: string;
age: number;
}
// Use Json.parse which returns Either<Error, Json>
const parseJSON = (input: string): E.Either<Error, unknown> =>
pipe(
J.parse(input),
E.mapLeft((e) => new Error(`Invalid JSON: ${e}`))
);
// Validation returns Either, making errors explicit in types
const validateUser = (data: unknown): E.Either<Error, User> => {
if (!data || typeof data !== 'object') {
return E.left(new Error('Data must be an object'));
}
const obj = data as Record<string, unknown>;
if (typeof obj.name !== 'string') {
return E.left(new Error('Name is required'));
}
if (typeof obj.age !== 'number') {
return E.left(new Error('Age must be a number'));
}
return E.right({ name: obj.name, age: obj.age });
};
// Compose with pipe and flatMap - errors propagate automatically
const processUserInput = (input: string): E.Either<Error, User> =>
pipe(
parseJSON(input),
E.flatMap(validateUser)
);
// Handle both cases explicitly
pipe(
processUserInput('{"name": "Alice", "age": 30}'),
E.match(
(error) => console.error('Failed to process user:', error.message),
(user) => console.log('User:', user)
)
);
T to Either<E, T> where E is your error typethrow new Error(...) to E.left(new Error(...))return value to E.right(value)pipe with E.flatMap to chain operationsasync function fetchUser(id: string): Promise<User> {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
return validateUser(data);
} catch (error) {
throw new Error(`Failed to fetch user: ${error}`);
}
}
async function fetchUserPosts(userId: string): Promise<Post[]> {
try {
const response = await fetch(`/api/users/${userId}/posts`);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return await response.json();
} catch (error) {
throw new Error(`Failed to fetch posts: ${error}`);
}
}
// Complex orchestration with try-catch
async function getUserWithPosts(id: string): Promise<{ user: User; posts: Post[] } | null> {
try {
const user = await fetchUser(id);
const posts = await fetchUserPosts(id);
return { user, posts };
} catch (error) {
console.error(error);
return null;
}
}
import * as TE from 'fp-ts/TaskEither';
import * as E from 'fp-ts/Either';
import { pipe } from 'fp-ts/function';
// Wrap fetch in TaskEither
const fetchUser = (id: string): TE.TaskEither<Error, User> =>
pipe(
TE.tryCatch(
() => fetch(`/api/users/${id}`),
(reason) => new Error(`Network error: ${reason}`)
),
TE.flatMap((response) =>
response.ok
? TE.right(response)
: TE.left(new Error(`HTTP error: ${response.status}`))
),
TE.flatMap((response) =>
TE.tryCatch(
() => response.json(),
(reason) => new Error(`JSON parse error: ${reason}`)
)
),
TE.flatMap((data) => TE.fromEither(validateUser(data)))
);
const fetchUserPosts = (userId: string): TE.TaskEither<Error, Post[]> =>
pipe(
TE.tryCatch(
() => fetch(`/api/users/${userId}/posts`),
(reason) => new Error(`Network error: ${reason}`)
),
TE.flatMap((response) =>
response.ok
? TE.right(response)
: TE.left(new Error(`HTTP error: ${response.status}`))
),
TE.flatMap((response) =>
TE.tryCatch(
() => response.json(),
(reason) => new Error(`JSON parse error: ${reason}`)
)
)
);
// Clean composition with automatic error propagation
const getUserWithPosts = (
id: string
): TE.TaskEither<Error, { user: User; posts: Post[] }> =>
pipe(
TE.Do,
TE.bind('user', () => fetchUser(id)),
TE.bind('posts', () => fetchUserPosts(id))
);
// Execute and handle results
const main = async () => {
const result = await getUserWithPosts('123')();
pipe(
result,
E.match(
(error) => console.error('Failed:', error.message),
({ user, posts }) => console.log('Success:', user, posts)
)
);
};
Create a reusable wrapper for functions that might throw:
import * as E from 'fp-ts/Either';
import * as TE from 'fp-ts/TaskEither';
// For sync functions
const tryCatchSync = <A>(f: () => A): E.Either<Error, A> =>
E.tryCatch(f, (e) => (e instanceof Error ? e : new Error(String(e))));
// For async functions
const tryCatchAsync = <A>(f: () => Promise<A>): TE.TaskEither<Error, A> =>
TE.tryCatch(f, (e) => (e instanceof Error ? e : new Error(String(e))));
---
interface Config {
database?: {
host?: string;
port?: number;
credentials?: {
username?: string;
password?: string;
};
};
}
function getDatabaseUrl(config: Config): string | null {
if (!config.database) {
return null;
}
if (!config.database.host) {
return null;
}
const port = config.database.port ?? 5432;
let auth = '';
if (config.database.credentials) {
if (config.database.credentials.username && config.database.credentials.password) {
auth = `${config.database.credentials.username}:${config.database.credentials.password}@`;
}
}
return `postgres://${auth}${config.database.host}:${port}`;
}
// Usage requires null check
const url = getDatabaseUrl(config);
if (url !== null) {
connectToDatabase(url);
} else {
console.error('Database URL not configured');
}
import * as O from 'fp-ts/Option';
import { pipe } from 'fp-ts/function';
const getDatabaseUrl = (config: Config): O.Option<string> =>
pipe(
O.fromNullable(config.database),
O.flatMap((db) =>
pipe(
O.fromNullable(db.host),
O.map((host) => {
const port = db.port ?? 5432;
const auth = pipe(
O.fromNullable(db.credentials),
O.flatMap((creds) =>
pipe(
O.Do,
O.bind('username', () => O.fromNullable(creds.username)),
O.bind('password', () => O.fromNullable(creds.password)),
O.map(({ username, password }) => `${username}:${password}@`)
)
),
O.getOrElse(() => '')
);
return `postgres://${auth}${host}:${port}`;
})
)
)
);
// Usage is explicit about the optional nature
pipe(
getDatabaseUrl(config),
O.match(
() => console.error('Database URL not configured'),
(url) => connectToDatabase(url)
)
);
interface User {
id: string;
name: string;
email: string;
}
function findUserById(users: User[], id: string): User | undefined {
return users.find((u) => u.id === id);
}
function getUserEmail(users: User[], id: string): string | null {
const user = findUserById(users, id);
if (!user) {
return null;
}
return user.email;
}
// Chained lookups get messy
function getManagerEmail(users: User[], employee: { managerId?: string }): string | null {
if (!employee.managerId) {
return null;
}
const manager = findUserById(users, employee.managerId);
if (!manager) {
return null;
}
return manager.email;
}
import * as O from 'fp-ts/Option';
import * as A from 'fp-ts/Array';
import { pipe } from 'fp-ts/function';
const findUserById = (users: User[], id: string): O.Option<User> =>
A.findFirst<User>((u) => u.id === id)(users);
const getUserEmail = (users: User[], id: string): O.Option<string> =>
pipe(
findUserById(users, id),
O.map((user) => user.email)
);
const getManagerEmail = (
users: User[],
employee: { managerId?: string }
): O.Option<string> =>
pipe(
O.fromNullable(employee.managerId),
O.flatMap((managerId) => findUserById(users, managerId)),
O.map((manager) => manager.email)
);
T | null, T | undefined, or optional propertiesT | null to Option<T>O.map, O.flatMap, O.filter instead of if statementsO.getOrElse, O.match, or O.toNullable when interfacing with non-fp codeimport * as O from 'fp-ts/Option';
import * as E from 'fp-ts/Either';
import { pipe } from 'fp-ts/function';
// Option to Either: provide error for None case
const optionToEither = <E, A>(onNone: () => E) => (
option: O.Option<A>
): E.Either<E, A> =>
pipe(
option,
E.fromOption(onNone)
);
// Example
const findUser = (id: string): O.Option<User> => /* ... */;
const getUser = (id: string): E.Either<Error, User> =>
pipe(
findUser(id),
E.fromOption(() => new Error(`User ${id} not found`))
);
---
import * as fs from 'fs';
function readFileCallback(
path: string,
callback: (error: Error | null, data: string | null) => void
): void {
fs.readFile(path, 'utf-8', (err, data) => {
if (err) {
callback(err, null);
} else {
callback(null, data);
}
});
}
function processFile(
inputPath: string,
outputPath: string,
callback: (error: Error | null) => void
): void {
readFileCallback(inputPath, (err, data) => {
if (err) {
callback(err);
return;
}
const processed = data!.toUpperCase();
fs.writeFile(outputPath, processed, (writeErr) => {
if (writeErr) {
callback(writeErr);
} else {
callback(null);
}
});
});
}
// Callback hell
function processMultipleFiles(
files: Array<{ input: string; output: string }>,
callback: (error: Error | null) => void
): void {
let completed = 0;
let hasError = false;
files.forEach(({ input, output }) => {
if (hasError) return;
processFile(input, output, (err) => {
if (hasError) return;
if (err) {
hasError = true;
callback(err);
return;
}
completed++;
if (completed === files.length) {
callback(null);
}
});
});
}
import * as fs from 'fs/promises';
import * as TE from 'fp-ts/TaskEither';
import * as A from 'fp-ts/Array';
import { pipe } from 'fp-ts/function';
// Wrap fs.promises in TaskEither
const readFile = (path: string): TE.TaskEither<Error, string> =>
TE.tryCatch(
() => fs.readFile(path, 'utf-8'),
(e) => (e instanceof Error ? e : new Error(String(e)))
);
const writeFile = (path: string, data: string): TE.TaskEither<Error, void> =>
TE.tryCatch(
() => fs.writeFile(path, data),
(e) => (e instanceof Error ? e : new Error(String(e)))
);
// Clean composition
const processFile = (
inputPath: string,
outputPath: string
): TE.TaskEither<Error, void> =>
pipe(
readFile(inputPath),
TE.map((data) => data.toUpperCase()),
TE.flatMap((processed) => writeFile(outputPath, processed))
);
// Process multiple files in parallel or sequence
const processMultipleFilesParallel = (
files: Array<{ input: string; output: string }>
): TE.TaskEither<Error, void[]> =>
pipe(
files,
A.traverse(TE.ApplicativePar)(({ input, output }) =>
processFile(input, output)
)
);
const processMultipleFilesSequential = (
files: Array<{ input: string; output: string }>
): TE.TaskEither<Error, void[]> =>
pipe(
files,
A.traverse(TE.ApplicativeSeq)(({ input, output }) =>
processFile(input, output)
)
);
import * as TE from 'fp-ts/TaskEither';
// Generic callback-to-TaskEither converter
const fromCallback = <A>(
f: (callback: (error: Error | null, result: A | null) => void) => void
): TE.TaskEither<Error, A> =>
() =>
new Promise((resolve) => {
f((error, result) => {
if (error) {
resolve({ _tag: 'Left', left: error });
} else {
resolve({ _tag: 'Right', right: result as A });
}
});
});
// Usage
const readFileLegacy = (path: string): TE.TaskEither<Error, string> =>
fromCallback((cb) => fs.readFile(path, 'utf-8', cb));
---
// Traditional class-based approach
interface Logger {
log(message: string): void;
error(message: string): void;
}
interface UserRepository {
findById(id: string): Promise<User | null>;
save(user: User): Promise<void>;
}
interface EmailService {
send(to: string, subject: string, body: string): Promise<void>;
}
class UserService {
constructor(
private readonly logger: Logger,
private readonly userRepo: UserRepository,
private readonly emailService: EmailService
) {}
async updateEmail(userId: string, newEmail: string): Promise<void> {
this.logger.log(`Updating email for user ${userId}`);
const user = await this.userRepo.findById(userId);
if (!user) {
this.logger.error(`User ${userId} not found`);
throw new Error(`User ${userId} not found`);
}
const oldEmail = user.email;
user.email = newEmail;
await this.userRepo.save(user);
await this.emailService.send(
oldEmail,
'Email Changed',
`Your email has been changed to ${newEmail}`
);
this.logger.log(`Email updated for user ${userId}`);
}
}
// Manual DI setup
const logger = new ConsoleLogger();
const userRepo = new PostgresUserRepository(dbConnection);
const emailService = new SmtpEmailService(smtpConfig);
const userService = new UserService(logger, userRepo, emailService);
import * as R from 'fp-ts/Reader';
import * as RTE from 'fp-ts/ReaderTaskEither';
import * as TE from 'fp-ts/TaskEither';
import { pipe } from 'fp-ts/function';
// Define the environment/dependencies as an interface
interface AppEnv {
logger: {
log: (message: string) => void;
error: (message: string) => void;
};
userRepo: {
findById: (id: string) => TE.TaskEither<Error, User | null>;
save: (user: User) => TE.TaskEither<Error, void>;
};
emailService: {
send: (to: string, subject: string, body: string) => TE.TaskEither<Error, void>;
};
}
// Helper to access environment
const ask = RTE.ask<AppEnv, Error>();
// Service functions using ReaderTaskEither
const logInfo = (message: string): RTE.ReaderTaskEither<AppEnv, Error, void> =>
pipe(
ask,
RTE.map((env) => env.logger.log(message))
);
const logError = (message: string): RTE.ReaderTaskEither<AppEnv, Error, void> =>
pipe(
ask,
RTE.map((env) => env.logger.error(message))
);
const findUser = (id: string): RTE.ReaderTaskEither<AppEnv, Error, User | null> =>
pipe(
ask,
RTE.flatMapTaskEither((env) => env.userRepo.findById(id))
);
const saveUser = (user: User): RTE.ReaderTaskEither<AppEnv, Error, void> =>
pipe(
ask,
RTE.flatMapTaskEither((env) => env.userRepo.save(user))
);
const sendEmail = (
to: string,
subject: string,
body: string
): RTE.ReaderTaskEither<AppEnv, Error, void> =>
pipe(
ask,
RTE.flatMapTaskEither((env) => env.emailService.send(to, subject, body))
);
// The updateEmail function using Reader composition
const updateEmail = (
userId: string,
newEmail: string
): RTE.ReaderTaskEither<AppEnv, Error, void> =>
pipe(
logInfo(`Updating email for user ${userId}`),
RTE.flatMap(() => findUser(userId)),
RTE.flatMap((user) => {
if (!user) {
return pipe(
logError(`User ${userId} not found`),
RTE.flatMap(() => RTE.left(new Error(`User ${userId} not found`)))
);
}
const oldEmail = user.email;
const updatedUser = { ...user, email: newEmail };
return pipe(
saveUser(updatedUser),
RTE.flatMap(() =>
sendEmail(
oldEmail,
'Email ChaWeekly roundup of top Claude Code skills, MCP servers, and AI coding tips.