What is an Effect?
AnEffect is a description of a program that may produce a value of type A, fail with an error of type E, or require services of type R. It’s a lazy, composable way to model side effects and computations.
The type signature is Effect<A, E, R> where:
Ais the success typeEis the error typeRis the required services/context
Writing Effect Code with Effect.gen
Prefer writing Effect code withEffect.gen for an imperative style similar to async/await. Use yield* to access the result of an effect.
Writing Effect Functions with Effect.fn
When writing functions that return an Effect, useEffect.fn to use the generator syntax. Avoid creating functions that return an Effect.gen, use Effect.fn instead.
Yielding Effects with yield*
InsideEffect.gen or Effect.fn, use yield* to unwrap the value from an Effect. This is similar to await with Promises.
Creating Effects from Common Sources
Effect provides multiple constructors for creating effects from different sources:From Plain Values
From Synchronous Code
From Code That May Throw
From Promise APIs
From Nullable Values
From Callback APIs
Best Practices
- Use
Effect.genfor imperative-style code blocks - Use
Effect.fnfor reusable Effect functions (notEffect.gen) - Always return when raising an error to help TypeScript’s control flow analysis
- Attach additional behavior with
.pipe()and combinators - Name your
Effect.fnfunctions to improve stack traces and tracing