<A, L>(iterator: LazyArg<Iterator<A, L>>, chunkSize?: number): Channel<
Arr.NonEmptyReadonlyArray<A>,
never,
L
>Creates a Channel from an iterator that emits arrays of elements.
Example (Batching iterator output)
import { Channel } from "effect"
// Create a channel from a simple iterator
const numberIterator = (): Iterator<number, string> => {
let count = 0
return {
next: () => {
if (count < 3) {
return { value: count++, done: false }
}
return { value: "finished", done: true }
}
}
}
const channel = Channel.fromIteratorArray(() => numberIterator(), 2)
// This will emit arrays: [0, 1], [2], then complete with "finished"Example (Batching generator output)
import { Channel } from "effect"
// Create channel from a generator function
function* fibonacci(): Generator<number, void, unknown> {
let a = 0, b = 1
for (let i = 0; i < 5; i++) {
yield a
;[a, b] = [b, a + b]
}
}
const fibChannel = Channel.fromIteratorArray(() => fibonacci(), 3)
// Emits: [0, 1, 1], [2, 3], then completesexport const const fromIteratorArray: <A, L>(
iterator: LazyArg<Iterator<A, L>>,
chunkSize?: number
) => Channel<
Arr.NonEmptyReadonlyArray<A>,
never,
L
>
Creates a Channel from an iterator that emits arrays of elements.
Example (Batching iterator output)
import { Channel } from "effect"
// Create a channel from a simple iterator
const numberIterator = (): Iterator<number, string> => {
let count = 0
return {
next: () => {
if (count < 3) {
return { value: count++, done: false }
}
return { value: "finished", done: true }
}
}
}
const channel = Channel.fromIteratorArray(() => numberIterator(), 2)
// This will emit arrays: [0, 1], [2], then complete with "finished"
Example (Batching generator output)
import { Channel } from "effect"
// Create channel from a generator function
function* fibonacci(): Generator<number, void, unknown> {
let a = 0, b = 1
for (let i = 0; i < 5; i++) {
yield a
;[a, b] = [b, a + b]
}
}
const fibChannel = Channel.fromIteratorArray(() => fibonacci(), 3)
// Emits: [0, 1, 1], [2, 3], then completes
fromIteratorArray = <function (type parameter) A in <A, L>(iterator: LazyArg<Iterator<A, L>>, chunkSize?: number): Channel<Arr.NonEmptyReadonlyArray<A>, never, L>A, function (type parameter) L in <A, L>(iterator: LazyArg<Iterator<A, L>>, chunkSize?: number): Channel<Arr.NonEmptyReadonlyArray<A>, never, L>L>(
iterator: LazyArg<Iterator<A, L>>iterator: type LazyArg<A> = () => AA zero-argument function that produces a value when invoked.
When to use
Use to type a lazy value provider that should not run until called.
Example (Creating a lazy argument)
import { Function } from "effect"
const constNull: Function.LazyArg<null> = Function.constant(null)
LazyArg<interface Iterator<T, TReturn = any, TNext = any>Iterator<function (type parameter) A in <A, L>(iterator: LazyArg<Iterator<A, L>>, chunkSize?: number): Channel<Arr.NonEmptyReadonlyArray<A>, never, L>A, function (type parameter) L in <A, L>(iterator: LazyArg<Iterator<A, L>>, chunkSize?: number): Channel<Arr.NonEmptyReadonlyArray<A>, never, L>L>>,
chunkSize: numberchunkSize = const DefaultChunkSize: numberThe default chunk size used by channels for batching operations.
Example (Reading the default chunk size)
import { Channel } from "effect"
console.log(Channel.DefaultChunkSize) // 4096
DefaultChunkSize
): interface Channel<out OutElem, out OutErr = never, out OutDone = void, in InElem = unknown, in InErr = unknown, in InDone = unknown, out Env = never>A Channel is a nexus of I/O operations, which supports both reading and
writing. A channel may read values of type InElem and write values of type
OutElem. When the channel finishes, it yields a value of type OutDone. A
channel may fail with a value of type OutErr.
Details
Channels are the foundation of Streams: both streams and sinks are built on
channels. Most users shouldn't have to use channels directly, as streams and
sinks are much more convenient and cover all common use cases. However, when
adding new stream and sink operators, or doing something highly specialized,
it may be useful to use channels directly.
Channels compose in a variety of ways:
- Piping: One channel can be piped to another channel, assuming the
input type of the second is the same as the output type of the first.
- Sequencing: The terminal value of one channel can be used to create
another channel, and both the first channel and the function that makes
the second channel can be composed into a channel.
- Concatenating: The output of one channel can be used to create other
channels, which are all concatenated together. The first channel and the
function that makes the other channels can be composed into a channel.
Example (Typing channels)
import type { Channel } from "effect"
// A channel that outputs numbers and requires no environment
type NumberChannel = Channel.Channel<number>
// A channel that outputs strings, can fail with Error, completes with boolean
type StringChannel = Channel.Channel<string, Error, boolean>
// A channel with all type parameters specified
type FullChannel = Channel.Channel<
string, // OutElem - output elements
Error, // OutErr - output errors
number, // OutDone - completion value
number, // InElem - input elements
string, // InErr - input errors
boolean, // InDone - input completion
{ db: string } // Env - required environment
>
Channel<import ArrArr.type Arr.NonEmptyReadonlyArray = /*unresolved*/ anyNonEmptyReadonlyArray<function (type parameter) A in <A, L>(iterator: LazyArg<Iterator<A, L>>, chunkSize?: number): Channel<Arr.NonEmptyReadonlyArray<A>, never, L>A>, never, function (type parameter) L in <A, L>(iterator: LazyArg<Iterator<A, L>>, chunkSize?: number): Channel<Arr.NonEmptyReadonlyArray<A>, never, L>L> =>
const fromPull: <
OutElem,
OutErr,
OutDone,
EX,
EnvX,
Env
>(
effect: Effect.Effect<
Pull.Pull<OutElem, OutErr, OutDone, EnvX>,
EX,
Env
>
) => Channel<
OutElem,
Pull.ExcludeDone<OutErr> | EX,
OutDone,
unknown,
unknown,
unknown,
Env | EnvX
>
Creates a Channel from an Effect that produces a Pull.
Example (Creating channels from pulls)
import { Channel, Effect } from "effect"
const channel = Channel.fromPull(
Effect.succeed(Effect.succeed(42))
)
fromPull(
import EffectEffect.const sync: <A>(
thunk: LazyArg<A>
) => Effect<A>
Creates an Effect that represents a synchronous side-effectful computation.
When to use
Use when you need to wrap a synchronous side-effectful operation that is not
expected to throw.
Details
The provided function is evaluated lazily when the effect runs.
Gotchas
The function must not throw. If it throws, the thrown value is treated as a
defect, not as a typed failure. Use try when throwing is expected.
Example (Capturing synchronous logging in an Effect)
import { Effect } from "effect"
const log = (message: string) =>
Effect.sync(() => {
console.log(message) // side effect
})
// ┌─── Effect<void, never, never>
// ▼
const program = log("Hello, World!")
sync(() => {
const const iter: Iterator<A, L, any>iter = iterator: LazyArg<Iterator<A, L>>iterator()
let let done: Option.Option<L>done = import OptionOption.const none: <A = never>() => Option<A>Creates an Option representing the absence of a value.
When to use
Use to represent a missing or uninitialized value, such as returning "no
result" from a function.
Details
- Returns
Option<never>, which is a subtype of Option<A> for any A
- Always returns the same singleton instance
Example (Creating an empty Option)
import { Option } from "effect"
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }
none<function (type parameter) L in <A, L>(iterator: LazyArg<Iterator<A, L>>, chunkSize?: number): Channel<Arr.NonEmptyReadonlyArray<A>, never, L>L>()
return import EffectEffect.const suspend: <A, E, R>(
effect: LazyArg<Effect<A, E, R>>
) => Effect<A, E, R>
Creates an Effect lazily, delaying construction until it is needed.
When to use
Use when you need to defer the evaluation of an effect until it is required.
Details
suspend takes a thunk that represents an effect and delays creating it
until the suspended effect is evaluated. This is useful for optimizing
expensive computations, managing circular dependencies such as recursive
functions, and helping TypeScript unify return types when branches construct
different effects. Any side effects or scoped captures inside the thunk are
re-executed on each invocation.
Example (Lazily evaluating side effects)
import { Effect } from "effect"
let i = 0
const bad = Effect.succeed(i++)
const good = Effect.suspend(() => Effect.succeed(i++))
console.log(Effect.runSync(bad)) // Output: 0
console.log(Effect.runSync(bad)) // Output: 0
console.log(Effect.runSync(good)) // Output: 1
console.log(Effect.runSync(good)) // Output: 2
Example (Suspending recursive Fibonacci evaluation)
import { Effect } from "effect"
const blowsUp = (n: number): Effect.Effect<number> =>
n < 2
? Effect.succeed(1)
: Effect.zipWith(blowsUp(n - 1), blowsUp(n - 2), (a, b) => a + b)
// console.log(Effect.runSync(blowsUp(32)))
// crash: JavaScript heap out of memory
const allGood = (n: number): Effect.Effect<number> =>
n < 2
? Effect.succeed(1)
: Effect.zipWith(
Effect.suspend(() => allGood(n - 1)),
Effect.suspend(() => allGood(n - 2)),
(a, b) => a + b
)
console.log(Effect.runSync(allGood(32)))
// Output: 3524578
Example (Helping TypeScript infer recursive effect types)
import { Effect } from "effect"
// Without suspend, TypeScript may struggle with type inference.
// Inferred type:
// (a: number, b: number) =>
// Effect<never, Error, never> | Effect<number, never, never>
const withoutSuspend = (a: number, b: number) =>
b === 0
? Effect.fail(new Error("Cannot divide by zero"))
: Effect.succeed(a / b)
// Using suspend to unify return types.
// Inferred type:
// (a: number, b: number) => Effect<number, Error, never>
const withSuspend = (a: number, b: number) =>
Effect.suspend(() =>
b === 0
? Effect.fail(new Error("Cannot divide by zero"))
: Effect.succeed(a / b)
)
suspend(() => {
if (let done: Option.Option<L>done._tag: "None" | "Some"_tag === "Some") return import CauseCause.done(let done: Option.Some<L>let done: {
_tag: "Some";
_op: "Some";
value: A;
valueOrUndefined: A;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
done.Some<L>.value: Lvalue)
const const buffer: A[]buffer: interface Array<T>Array<function (type parameter) A in <A, L>(iterator: LazyArg<Iterator<A, L>>, chunkSize?: number): Channel<Arr.NonEmptyReadonlyArray<A>, never, L>A> = []
while (const buffer: A[]buffer.Array<T>.length: numberGets or sets the length of the array. This is a number one higher than the highest index in the array.
length < chunkSize: numberchunkSize) {
const const state: IteratorResult<A, L>state = const iter: Iterator<A, L, any>iter.Iterator<A, L, any>.next(...[value]: [] | [any]): IteratorResult<A, L>next()
if (const state: IteratorResult<A, L>state.done?: boolean | undefineddone) {
if (const buffer: A[]buffer.Array<T>.length: numberGets or sets the length of the array. This is a number one higher than the highest index in the array.
length === 0) {
return import CauseCause.done(const state: IteratorReturnResult<L>state.IteratorReturnResult<L>.value: Lvalue)
}
let done: Option.Option<L>done = import OptionOption.const some: <A>(value: A) => Option<A>Wraps the given value into an Option to represent its presence.
When to use
Use to wrap a known present value as Option
- Returning a successful result from a partial function
Details
- Always returns
Some<A>
- Does not filter
null or undefined; use
fromNullishOr
for that
Example (Wrapping a value)
import { Option } from "effect"
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }
some(const state: IteratorReturnResult<L>state.IteratorReturnResult<L>.value: Lvalue)
break
}
const buffer: A[]buffer.Array<A>.push(...items: A[]): numberAppends new elements to the end of an array, and returns the new length of the array.
push(const state: IteratorYieldResult<A>state.IteratorYieldResult<A>.value: Avalue)
}
return import EffectEffect.const succeed: <A>(value: A) => Effect<A>Creates an Effect that always succeeds with a given value.
When to use
Use when an effect should complete successfully with a specific value without any errors
or external dependencies.
Example (Creating a successful effect)
import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)
succeed(const buffer: A[]buffer as any as import ArrArr.type Arr.NonEmptyReadonlyArray = /*unresolved*/ anyNonEmptyReadonlyArray<function (type parameter) A in <A, L>(iterator: LazyArg<Iterator<A, L>>, chunkSize?: number): Channel<Arr.NonEmptyReadonlyArray<A>, never, L>A>)
})
})
)