What is Effect-TS
Effect-TS is a library that enables functional programming in TypeScript. It provides type-safe error handling, dependency injection, and concurrency, allowing you to build robust applications.
Basic Concepts
The Effect Type
Effect<A, E, R> has three type parameters.
Effect<
A, // Type of successful return value
E, // Type of possible errors
R // Required dependencies (Requirements)
>
Basic Usage
Creating Effects
import { Effect } from 'effect';
// Successful Effect
const success = Effect.succeed(42);
// Failing Effect
const failure = Effect.fail(new Error('Something went wrong'));
// Async Effect
const asyncEffect = Effect.promise(() => fetch('/api/data').then(r => r.json()));
// Catching exceptions
const safe = Effect.try({
try: () => JSON.parse(invalidJson),
catch: (error) => new ParseError(error)
});
Running Effects
import { Effect } from 'effect';
const program = Effect.succeed(42);
// Synchronous execution
const result = Effect.runSync(program);
// Asynchronous execution
const promise = Effect.runPromise(program);
// Promise (returns error as Either type)
const exit = await Effect.runPromiseExit(program);
Error Handling
Type-Safe Errors
import { Effect, Data } from 'effect';
// Define custom errors
class NetworkError extends Data.TaggedError('NetworkError')<{
message: string;
}> {}
class ValidationError extends Data.TaggedError('ValidationError')<{
field: string;
message: string;
}> {}
// Function that may produce errors
const fetchUser = (id: string): Effect.Effect<
User,
NetworkError | ValidationError
> => {
if (!id) {
return Effect.fail(new ValidationError({ field: 'id', message: 'Required' }));
}
return Effect.tryPromise({
try: () => fetch(`/api/users/${id}`).then(r => r.json()),
catch: () => new NetworkError({ message: 'Failed to fetch' })
});
};
Handling Errors
const program = fetchUser('123').pipe(
// Catch specific error
Effect.catchTag('NetworkError', (e) =>
Effect.succeed({ name: 'Fallback User' })
),
// Catch all errors
Effect.catchAll((e) => Effect.succeed({ name: 'Default' }))
);
Dependency Injection
Defining Services
import { Context, Effect, Layer } from 'effect';
// Service interface
class Database extends Context.Tag('Database')<
Database,
{
query: (sql: string) => Effect.Effect<unknown[]>;
}
>() {}
// Function using the service
const getUsers = Effect.gen(function* () {
const db = yield* Database;
return yield* db.query('SELECT * FROM users');
});
// Implementation
const DatabaseLive = Layer.succeed(Database, {
query: (sql) => Effect.promise(() => pool.query(sql))
});
// Test mock
const DatabaseTest = Layer.succeed(Database, {
query: () => Effect.succeed([{ id: 1, name: 'Test' }])
});
// Execution
const program = getUsers.pipe(
Effect.provide(DatabaseLive)
);
Concurrency
Parallel Execution
import { Effect } from 'effect';
const task1 = Effect.promise(() => fetch('/api/users'));
const task2 = Effect.promise(() => fetch('/api/posts'));
const task3 = Effect.promise(() => fetch('/api/comments'));
// Execute all in parallel
const all = Effect.all([task1, task2, task3], { concurrency: 'unbounded' });
// Limit concurrency
const limited = Effect.all([task1, task2, task3], { concurrency: 2 });
// Get first completed
const race = Effect.race([task1, task2, task3]);
Resource Management
import { Effect } from 'effect';
const acquire = Effect.promise(() => pool.connect());
const release = (conn: Connection) => Effect.promise(() => conn.release());
const withConnection = Effect.acquireUseRelease(
acquire,
(conn) => Effect.promise(() => conn.query('SELECT 1')),
release
);
Pipeline
import { Effect, pipe } from 'effect';
const program = pipe(
Effect.succeed({ name: 'Alice', age: 30 }),
Effect.map(user => user.name),
Effect.flatMap(name => Effect.succeed(`Hello, ${name}!`)),
Effect.tap(greeting => Effect.log(greeting))
);
// Or
const program2 = Effect.succeed({ name: 'Alice', age: 30 }).pipe(
Effect.map(user => user.name),
Effect.flatMap(name => Effect.succeed(`Hello, ${name}!`))
);
Generator Syntax
import { Effect } from 'effect';
const program = Effect.gen(function* () {
const user = yield* fetchUser('123');
const posts = yield* fetchPosts(user.id);
const comments = yield* fetchComments(posts[0].id);
return { user, posts, comments };
});
Scheduling
import { Effect, Schedule } from 'effect';
// Retry strategy
const retry = Schedule.exponential('100 millis').pipe(
Schedule.compose(Schedule.recurs(3))
);
const program = fetchData.pipe(
Effect.retry(retry)
);
// Repeated execution
const repeated = Effect.repeat(
fetchData,
Schedule.spaced('1 minute')
);
Summary
Effect-TS adds powerful functional programming capabilities to TypeScript. With type-safe error handling, dependency injection, and concurrency, you can build maintainable and reliable applications.
← Back to list