Skip to content

配置

配置是任何云原生应用程序的重要方面。Effect通过为配置提供者提供便捷的接口来简化配置管理过程。

Effect中的配置前端使生态系统库和应用程序能够以声明性方式指定其配置要求。它将复杂的任务卸载给ConfigProvider,该提供者可以由第三方库提供。

Effect捆绑了一个简单的默认ConfigProvider,它从环境变量中检索配置数据。此默认提供者可在开发期间使用,或作为过渡到更高级配置提供者之前的起点。

要使我们的应用程序可配置,我们需要理解三个基本要素:

  • 配置描述:我们使用Config<A>的实例来描述配置数据。如果配置数据很简单,例如stringnumberboolean,我们可以使用Config模块提供的内置函数。对于更复杂的数据类型,如HostPort,我们可以组合原始配置来创建自定义配置描述。

  • 配置前端:我们利用Config<A>的实例来加载实例描述的配置数据(Config本身就是一个效果)。此过程利用当前的ConfigProvider来检索配置。

  • 配置后端ConfigProvider作为管理配置加载过程的底层引擎。Effect作为其默认服务的一部分带有默认配置提供者。此默认提供者从环境变量中读取配置数据。如果我们想使用自定义配置提供者,我们可以利用Effect.withConfigProvider API来相应地配置Effect运行时。

Effect为配置值提供了几种内置类型,您可以直接使用:

类型描述
string将配置值读取为字符串。
number将值读取为浮点数。
boolean将值读取为布尔值(truefalse)。
integer将值读取为整数。
date将值解析为Date对象。
literal读取固定字面量(*)。
logLevel将值读取为LogLevel
duration将值解析为时间持续时间。
redacted读取敏感值,确保在记录时受到保护。
url将值解析为有效的URL。

(*) string | number | boolean | null | bigint

示例(加载环境变量)

以下是使用环境变量加载HOSTPORT基本配置的示例:

primitives.ts
import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Config
Config
} from "effect"
// 定义一个加载HOST和PORT配置的程序
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<string, ConfigError, never>> | YieldWrap<Effect.Effect<number, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<string, ConfigError, never>> | YieldWrap<Effect.Effect<number, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
const
const host: string
host
= yield*
import Config
Config
.
const string: (name?: string) => Config.Config<string>

Constructs a config for a string value.

@since2.0.0

string
("HOST") // 读取为字符串
const
const port: number
port
= yield*
import Config
Config
.
const number: (name?: string) => Config.Config<number>

Constructs a config for a float value.

@since2.0.0

number
("PORT") // 读取为数字
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`Application started: ${
const host: string
host
}:${
const port: number
port
}`)
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
const program: Effect.Effect<void, ConfigError, never>
program
)

如果您在未设置所需环境变量的情况下运行此程序:

Terminal window
npx tsx primitives.ts

您将看到指示缺少配置的错误:

Terminal window
[Error: (Missing data at HOST: "Expected HOST to exist in the process context")] {
name: '(FiberFailure) Error',
[Symbol(effect/Runtime/FiberFailure)]: Symbol(effect/Runtime/FiberFailure),
[Symbol(effect/Runtime/FiberFailure/Cause)]: {
_tag: 'Fail',
error: {
_op: 'MissingData',
path: [ 'HOST' ],
message: 'Expected HOST to exist in the process context'
}
}
}

要成功运行程序,请按如下所示设置环境变量:

Terminal window
HOST=localhost PORT=8080 npx tsx primitives.ts

输出:

Terminal window
Application started: localhost:8080

您可以使用schema定义和解码配置值。

示例(解码配置值)

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Schema
Schema
} from "effect"
// 定义一个期望至少4个字符的字符串的配置
const
const myConfig: Config<string>
myConfig
=
import Schema
Schema
.
const Config: <string, string>(name: string, schema: Schema.Schema<string, string, never>) => Config<string>

@since3.10.0

Config
(
"Foo",
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Pipeable.pipe<typeof Schema.String, Schema.filter<typeof Schema.String>>(this: typeof Schema.String, ab: (_: typeof Schema.String) => Schema.filter<typeof Schema.String>): Schema.filter<typeof Schema.String> (+21 overloads)
pipe
(
import Schema
Schema
.
const minLength: <typeof Schema.String>(minLength: number, annotations?: Schema.Annotations.Filter<string, string> | undefined) => <A>(self: typeof Schema.String & Schema.Schema<A, string, never>) => Schema.filter<typeof Schema.String>

@since3.10.0

minLength
(4))
)

有关更多信息,请参阅Schema.Config文档。

有时,您可能遇到环境变量缺失的情况,导致配置不完整。为了解决这个问题,Effect提供了Config.withDefault函数,允许您指定默认值。这种回退机制确保即使未设置所需的环境变量,您的应用程序也能继续运行。

示例(使用默认值)

defaults.ts
import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Config
Config
} from "effect"
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<string, ConfigError, never>> | YieldWrap<Effect.Effect<number, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<string, ConfigError, never>> | YieldWrap<Effect.Effect<number, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
const
const host: string
host
= yield*
import Config
Config
.
const string: (name?: string) => Config.Config<string>

Constructs a config for a string value.

@since2.0.0

string
("HOST")
// 如果未设置PORT,则使用默认值8080
const
const port: number
port
= yield*
import Config
Config
.
const number: (name?: string) => Config.Config<number>

Constructs a config for a float value.

@since2.0.0

number
("PORT").
Pipeable.pipe<Config.Config<number>, Config.Config<number>>(this: Config.Config<number>, ab: (_: Config.Config<number>) => Config.Config<number>): Config.Config<number> (+21 overloads)
pipe
(
import Config
Config
.
const withDefault: <8080>(def: 8080) => <A>(self: Config.Config<A>) => Config.Config<8080 | A> (+1 overload)

Returns a config that describes the same structure as this one, but has the specified default value in case the information cannot be found.

@since2.0.0

withDefault
(8080))
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`Application started: ${
const host: string
host
}:${
const port: number
port
}`)
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
const program: Effect.Effect<void, ConfigError, never>
program
)

仅设置HOST环境变量运行此程序:

Terminal window
HOST=localhost npx tsx defaults.ts

产生以下输出:

Terminal window
Application started: localhost:8080

在这种情况下,即使未设置PORT环境变量,程序仍继续运行,使用端口的默认值8080。这确保应用程序保持功能性,而无需明确提供每个配置。

某些配置值(如API密钥)不应在日志中打印。

Config.redacted函数用于安全处理敏感信息。 它解析配置值并将其包装在Redacted<string>中,这是一个专门设计用于保护机密的数据类型

当您使用console.log记录Redacted值时,实际内容保持隐藏,提供额外的安全层。要访问真实值,您必须显式使用Redacted.value

示例(保护敏感数据)

redacted.ts
import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Config
Config
,
import Redacted
Redacted
} from "effect"
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<Redacted.Redacted<string>, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<Redacted.Redacted<string>, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
// ┌─── Redacted<string>
// ▼
const
const redacted: Redacted.Redacted<string>
redacted
= yield*
import Config
Config
.
const redacted: (name?: string) => Config.Config<Redacted.Redacted> (+1 overload)

Constructs a config for a redacted value.

@since2.0.0

redacted
("API_KEY")
// 记录脱敏值,不会泄露实际机密
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`Console output: ${
const redacted: Redacted.Redacted<string>
redacted
}`)
// 使用Redacted.value访问真实值并记录它
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`Actual value: ${
import Redacted
Redacted
.
const value: <string>(self: Redacted.Redacted<string>) => string

Retrieves the original value from a Redacted instance. Use this function with caution, as it exposes the sensitive data.

@example

import * as assert from "node:assert"
import { Redacted } from "effect"
const API_KEY = Redacted.make("1234567890")
assert.equal(Redacted.value(API_KEY), "1234567890")

@since3.3.0

value
(
const redacted: Redacted.Redacted<string>
redacted
)}`)
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
const program: Effect.Effect<void, ConfigError, never>
program
)

当执行此程序时:

Terminal window
API_KEY=my-api-key tsx redacted.ts

输出将如下所示:

Terminal window
Console output: <redacted>
Actual value: my-api-key

如所示,当使用console.log记录Redacted值时,输出为<redacted>,确保敏感数据保持隐藏。但是,通过使用Redacted.value,可以访问和显示真实值("my-api-key"),提供对机密的受控访问。

默认情况下,当您将字符串传递给Config.redacted时,它返回Redacted<string>。您也可以传递Config(如Config.number)以确保只接受经过验证的值。这通过确保敏感数据在脱敏之前得到适当验证来增加额外的安全层。

示例(脱敏和验证数字)

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Config
Config
,
import Redacted
Redacted
} from "effect"
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<Redacted.Redacted<number>, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<Redacted.Redacted<number>, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
// 使用脱敏包装经过验证的数字配置
//
// ┌─── Redacted<number>
// ▼
const
const redacted: Redacted.Redacted<number>
redacted
= yield*
import Config
Config
.
const redacted: <number>(config: Config.Config<number>) => Config.Config<Redacted.Redacted<number>> (+1 overload)

Constructs a config for a redacted value.

@since2.0.0

redacted
(
import Config
Config
.
const number: (name?: string) => Config.Config<number>

Constructs a config for a float value.

@since2.0.0

number
("SECRET"))
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`Console output: ${
const redacted: Redacted.Redacted<number>
redacted
}`)
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`Actual value: ${
import Redacted
Redacted
.
const value: <number>(self: Redacted.Redacted<number>) => number

Retrieves the original value from a Redacted instance. Use this function with caution, as it exposes the sensitive data.

@example

import * as assert from "node:assert"
import { Redacted } from "effect"
const API_KEY = Redacted.make("1234567890")
assert.equal(Redacted.value(API_KEY), "1234567890")

@since3.3.0

value
(
const redacted: Redacted.Redacted<number>
redacted
)}`)
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
const program: Effect.Effect<void, ConfigError, never>
program
)

Effect提供了几个内置组合器,允许您定义和操作配置。 这些组合器接受Config作为输入并产生另一个Config,从而实现更复杂的配置结构。

组合器描述
array为值数组构造配置。
chunk为值序列构造配置。
option返回可选配置。如果数据缺失,结果将是None;否则,将是Some
repeat描述值序列,每个值都遵循给定配置的结构。
hashSet为值集合构造配置。
hashMap为键值映射构造配置。

此外,还有三个用于特定用例的特殊组合器:

组合器描述
succeed构造包含预定义值的配置。
fail构造使用指定错误消息失败的配置。
all将多个配置组合成元组、结构或参数列表。

示例(使用array组合器)

以下示例演示如何使用Config.array构造函数将环境变量加载为字符串数组。

index.ts
import {
import Config
Config
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<string[], ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<string[], ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
const
const config: string[]
config
= yield*
import Config
Config
.
const array: <string>(config: Config.Config<string>, name?: string) => Config.Config<string[]>

Constructs a config for an array of values.

@since2.0.0

array
(
import Config
Config
.
const string: (name?: string) => Config.Config<string>

Constructs a config for a string value.

@since2.0.0

string
(), "MYARRAY")
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
const config: string[]
config
)
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
const program: Effect.Effect<void, ConfigError, never>
program
)
// Run:
// MYARRAY=a,b,c,a npx tsx index.ts
// Output:
// [ 'a', 'b', 'c', 'a' ]

示例(使用hashSet组合器)

index.ts
import {
import Config
Config
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<HashSet<string>, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<HashSet<string>, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
const
const config: HashSet<string>
config
= yield*
import Config
Config
.
const hashSet: <string>(config: Config.Config<string>, name?: string) => Config.Config<HashSet<string>>

Constructs a config for a sequence of values.

@since2.0.0

hashSet
(
import Config
Config
.
const string: (name?: string) => Config.Config<string>

Constructs a config for a string value.

@since2.0.0

string
(), "MYSET")
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
const config: HashSet<string>
config
)
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
const program: Effect.Effect<void, ConfigError, never>
program
)
// Run:
// MYSET=a,"b c",d,a npx tsx index.ts
// Output:
// { _id: 'HashSet', values: [ 'd', 'a', 'b c' ] }

示例(使用hashMap组合器)

index.ts
import {
import Config
Config
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<HashMap<string, string>, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<HashMap<string, string>, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
const
const config: HashMap<string, string>
config
= yield*
import Config
Config
.
const hashMap: <string>(config: Config.Config<string>, name?: string) => Config.Config<HashMap<string, string>>

Constructs a config for a sequence of values.

@since2.0.0

hashMap
(
import Config
Config
.
const string: (name?: string) => Config.Config<string>

Constructs a config for a string value.

@since2.0.0

string
(), "MYMAP")
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
const config: HashMap<string, string>
config
)
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
const program: Effect.Effect<void, ConfigError, never>
program
)
// Run:
// MYMAP_A=a MYMAP_B=b npx tsx index.ts
// Output:
// { _id: 'HashMap', values: [ [ 'A', 'a' ], [ 'B', 'b' ] ] }

Effect提供了几个内置操作符来处理配置,允许您根据需要操作和转换它们。

这些操作符使您能够修改配置或验证其值:

操作符描述
validate确保配置满足某些条件,如果不满足则返回验证错误。
map使用提供的函数转换配置的值。
mapAttempt类似于map,但捕获函数抛出的任何错误并将其转换为验证错误。
mapOrFail类似于map,但函数可能失败。如果失败,结果是验证错误。

示例(使用validate操作符)

validate.ts
import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Config
Config
} from "effect"
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<string, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<string, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
// 加载NAME环境变量并验证其长度
const
const config: string
config
= yield*
import Config
Config
.
const string: (name?: string) => Config.Config<string>

Constructs a config for a string value.

@since2.0.0

string
("NAME").
Pipeable.pipe<Config.Config<string>, Config.Config<string>>(this: Config.Config<string>, ab: (_: Config.Config<string>) => Config.Config<string>): Config.Config<string> (+21 overloads)
pipe
(
import Config
Config
.
const validate: <string>(options: {
readonly message: string;
readonly validation: Predicate<string>;
}) => (self: Config.Config<string>) => Config.Config<string> (+3 overloads)

Returns a config that describes the same structure as this one, but which performs validation during loading.

@since2.0.0

validate
({
message: string
message
: "Expected a string at least 4 characters long",
validation: Predicate<string>
validation
: (
s: string
s
) =>
s: string
s
.
String.length: number

Returns the length of a String object.

length
>= 4
})
)
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
const config: string
config
)
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
const program: Effect.Effect<void, ConfigError, never>
program
)

如果我们使用无效的NAME值运行此程序:

Terminal window
NAME=foo npx tsx validate.ts

输出将是:

Terminal window
[Error: (Invalid data at NAME: "Expected a string at least 4 characters long")] {
name: '(FiberFailure) Error',
[Symbol(effect/Runtime/FiberFailure)]: Symbol(effect/Runtime/FiberFailure),
[Symbol(effect/Runtime/FiberFailure/Cause)]: {
_tag: 'Fail',
error: {
_op: 'InvalidData',
path: [ 'NAME' ],
message: 'Expected a string at least 4 characters long'
}
}
}

当您想要在出现错误或数据缺失时提供替代配置时,回退操作符很有用。这些操作符确保即使某些配置值不可用,您的程序仍能运行。

操作符描述
orElse首先尝试使用主配置。如果失败或缺失,则回退到另一个配置。
orElseIf类似于orElse,但仅在错误匹配条件时才切换到回退配置。

示例(使用orElse进行回退)

在此示例中,程序需要两个配置值:AB。我们设置了两个配置提供者,每个都只包含所需值中的一个。使用orElse操作符,我们组合这些提供者,以便程序可以检索AB

orElse.ts
import {
import Config
Config
,
import ConfigProvider
ConfigProvider
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
// 需要两个配置的程序:A和B
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<string, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<string, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
const
const A: string
A
= yield*
import Config
Config
.
const string: (name?: string) => Config.Config<string>

Constructs a config for a string value.

@since2.0.0

string
("A") // 检索配置A
const
const B: string
B
= yield*
import Config
Config
.
const string: (name?: string) => Config.Config<string>

Constructs a config for a string value.

@since2.0.0

string
("B") // 检索配置B
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`A: ${
const A: string
A
}, B: ${
const B: string
B
}`)
})
// 第一个提供者有A但缺少B
const
const provider1: ConfigProvider.ConfigProvider
provider1
=
import ConfigProvider
ConfigProvider
.
const fromMap: (map: Map<string, string>, config?: Partial<ConfigProvider.ConfigProvider.FromMapConfig>) => ConfigProvider.ConfigProvider

Constructs a ConfigProvider using a map and the specified delimiter string, which determines how to split the keys in the map into path segments.

@since2.0.0

fromMap
(new
var Map: MapConstructor
new <string, string>(iterable?: Iterable<readonly [string, string]> | null | undefined) => Map<string, string> (+3 overloads)
Map
([["A", "A"]]))
// 第二个提供者有B但缺少A
const
const provider2: ConfigProvider.ConfigProvider
provider2
=
import ConfigProvider
ConfigProvider
.
const fromMap: (map: Map<string, string>, config?: Partial<ConfigProvider.ConfigProvider.FromMapConfig>) => ConfigProvider.ConfigProvider

Constructs a ConfigProvider using a map and the specified delimiter string, which determines how to split the keys in the map into path segments.

@since2.0.0

fromMap
(new
var Map: MapConstructor
new <string, string>(iterable?: Iterable<readonly [string, string]> | null | undefined) => Map<string, string> (+3 overloads)
Map
([["B", "B"]]))
// 使用`orElse`从provider1回退到provider2
const
const provider: ConfigProvider.ConfigProvider
provider
=
const provider1: ConfigProvider.ConfigProvider
provider1
.
Pipeable.pipe<ConfigProvider.ConfigProvider, ConfigProvider.ConfigProvider>(this: ConfigProvider.ConfigProvider, ab: (_: ConfigProvider.ConfigProvider) => ConfigProvider.ConfigProvider): ConfigProvider.ConfigProvider (+21 overloads)
pipe
(
import ConfigProvider
ConfigProvider
.
const orElse: (that: LazyArg<ConfigProvider.ConfigProvider>) => (self: ConfigProvider.ConfigProvider) => ConfigProvider.ConfigProvider (+1 overload)

Returns a new config provider that preferentially loads configuration data from this one, but which will fall back to the specified alternate provider if there are any issues loading the configuration from this provider.

@since2.0.0

orElse
(() =>
const provider2: ConfigProvider.ConfigProvider
provider2
))
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const withConfigProvider: <void, ConfigError, never>(self: Effect.Effect<void, ConfigError, never>, provider: ConfigProvider.ConfigProvider) => Effect.Effect<void, ConfigError, never> (+1 overload)

Executes an effect using a specific configuration provider.

Details

This function lets you run an effect with a specified configuration provider. The custom provider will override the default configuration provider for the duration of the effect's execution.

When to Use

This is particularly useful when you need to use a different set of configuration values or sources for specific parts of your application.

Example

import { Config, ConfigProvider, Effect } from "effect"
const customProvider: ConfigProvider.ConfigProvider = ConfigProvider.fromMap(
new Map([["custom-key", "custom-value"]])
)
const program = Effect.withConfigProvider(customProvider)(
Effect.gen(function*() {
const value = yield* Config.string("custom-key")
console.log(`Config value: ${value}`)
})
)
Effect.runPromise(program)
// Output:
// Config value: custom-value

@since2.0.0

withConfigProvider
(
const program: Effect.Effect<void, ConfigError, never>
program
,
const provider: ConfigProvider.ConfigProvider
provider
))

如果我们运行此程序:

Terminal window
npx tsx orElse.ts

输出将是:

Terminal window
A: A, B: B

Effect允许您通过使用组合器操作符组合原始配置来为自定义类型定义配置。

例如,让我们创建一个HostPort类,它有两个字段:hostport

class
class HostPort
HostPort
{
constructor(readonly
HostPort.host: string
host
: string, readonly
HostPort.port: number
port
: number) {}
get
HostPort.url: string
url
() {
return `${this.
HostPort.host: string
host
}:${this.
HostPort.port: number
port
}`
}
}

要为此自定义类型定义配置,我们可以组合stringnumber的原始配置:

示例(定义自定义配置)

import {
import Config
Config
} from "effect"
class
class HostPort
HostPort
{
constructor(readonly
HostPort.host: string
host
: string, readonly
HostPort.port: number
port
: number) {}
get
HostPort.url: string
url
() {
return `${this.
HostPort.host: string
host
}:${this.
HostPort.port: number
port
}`
}
}
// 组合'HOST'和'PORT'的配置
const
const both: Config.Config<[string, number]>
both
=
import Config
Config
.
const all: <readonly [Config.Config<string>, Config.Config<number>]>(arg: readonly [Config.Config<string>, Config.Config<number>]) => Config.Config<[string, number]>

Constructs a config from a tuple / struct / arguments of configs.

@since2.0.0

all
([
import Config
Config
.
const string: (name?: string) => Config.Config<string>

Constructs a config for a string value.

@since2.0.0

string
("HOST"),
import Config
Config
.
const number: (name?: string) => Config.Config<number>

Constructs a config for a float value.

@since2.0.0

number
("PORT")])
// 将配置值映射到HostPort实例
const
const config: Config.Config<HostPort>
config
=
import Config
Config
.
const map: <[string, number], HostPort>(self: Config.Config<[string, number]>, f: (a: [string, number]) => HostPort) => Config.Config<HostPort> (+1 overload)

Returns a config whose structure is the same as this one, but which produces a different value, constructed using the specified function.

@since2.0.0

map
(
const both: Config.Config<[string, number]>
both
,
([
host: string
host
,
port: number
port
]) => new
constructor HostPort(host: string, port: number): HostPort
HostPort
(
host: string
host
,
port: number
port
)
)

在此示例中,Config.all(configs)将两个原始配置Config<string>Config<number>组合成Config<[string, number]>。然后使用Config.map操作符将这些值转换为HostPort类的实例。

示例(使用自定义配置)

App.ts
import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Config
Config
} from "effect"
class
class HostPort
HostPort
{
constructor(readonly
HostPort.host: string
host
: string, readonly
HostPort.port: number
port
: number) {}
get
HostPort.url: string
url
() {
return `${this.
HostPort.host: string
host
}:${this.
HostPort.port: number
port
}`
}
}
// Combine the configuration for 'HOST' and 'PORT'
const
const both: Config.Config<[string, number]>
both
=
import Config
Config
.
const all: <readonly [Config.Config<string>, Config.Config<number>]>(arg: readonly [Config.Config<string>, Config.Config<number>]) => Config.Config<[string, number]>

Constructs a config from a tuple / struct / arguments of configs.

@since2.0.0

all
([
import Config
Config
.
const string: (name?: string) => Config.Config<string>

Constructs a config for a string value.

@since2.0.0

string
("HOST"),
import Config
Config
.
const number: (name?: string) => Config.Config<number>

Constructs a config for a float value.

@since2.0.0

number
("PORT")])
// Map the configuration values into a HostPort instance
const
const config: Config.Config<HostPort>
config
=
import Config
Config
.
const map: <[string, number], HostPort>(self: Config.Config<[string, number]>, f: (a: [string, number]) => HostPort) => Config.Config<HostPort> (+1 overload)

Returns a config whose structure is the same as this one, but which produces a different value, constructed using the specified function.

@since2.0.0

map
(
const both: Config.Config<[string, number]>
both
,
([
host: string
host
,
port: number
port
]) => new
constructor HostPort(host: string, port: number): HostPort
HostPort
(
host: string
host
,
port: number
port
)
)
// 读取配置并启动应用程序的主程序
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<HostPort, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<HostPort, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
const
const hostPort: HostPort
hostPort
= yield*
const config: Config.Config<HostPort>
config
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`Application started: ${
const hostPort: HostPort
hostPort
.
HostPort.url: string
url
}`)
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
const program: Effect.Effect<void, ConfigError, never>
program
)

当您运行此程序时,它将尝试从环境变量中检索HOSTPORT的值:

Terminal window
HOST=localhost PORT=8080 npx tsx App.ts

如果成功,它将打印:

Terminal window
Application started: localhost:8080

我们已经看到如何在顶层定义配置,无论是原始类型还是自定义类型。但在某些情况下,您可能希望以更嵌套的方式构造配置,将它们组织在公共命名空间下以提高清晰度和可管理性。

例如,考虑以下ServiceConfig类型:

class
class ServiceConfig
ServiceConfig
{
constructor(
readonly
ServiceConfig.host: string
host
: string,
readonly
ServiceConfig.port: number
port
: number,
readonly
ServiceConfig.timeout: number
timeout
: number
) {}
get
ServiceConfig.url: string
url
() {
return `${this.
ServiceConfig.host: string
host
}:${this.
ServiceConfig.port: number
port
}`
}
}

如果您在应用程序中使用此配置,它将期望在顶层有HOSTPORTTIMEOUT环境变量。但在许多情况下,您可能希望在共享命名空间下组织配置——例如,将HOSTPORT分组在SERVER命名空间下,同时将TIMEOUT保留在根目录。

为此,您可以使用Config.nested操作符,它允许您在特定命名空间下嵌套配置值。让我们更新前面的示例以反映这一点:

import {
import Config
Config
} from "effect"
class
class ServiceConfig
ServiceConfig
{
constructor(
readonly
ServiceConfig.host: string
host
: string,
readonly
ServiceConfig.port: number
port
: number,
readonly
ServiceConfig.timeout: number
timeout
: number
) {}
get
ServiceConfig.url: string
url
() {
return `${this.
ServiceConfig.host: string
host
}:${this.
ServiceConfig.port: number
port
}`
}
}
const
const serverConfig: Config.Config<[string, number]>
serverConfig
=
import Config
Config
.
const all: <readonly [Config.Config<string>, Config.Config<number>]>(arg: readonly [Config.Config<string>, Config.Config<number>]) => Config.Config<[string, number]>

Constructs a config from a tuple / struct / arguments of configs.

@since2.0.0

all
([
import Config
Config
.
const string: (name?: string) => Config.Config<string>

Constructs a config for a string value.

@since2.0.0

string
("HOST"),
import Config
Config
.
const number: (name?: string) => Config.Config<number>

Constructs a config for a float value.

@since2.0.0

number
("PORT")
])
const
const serviceConfig: Config.Config<ServiceConfig>
serviceConfig
=
import Config
Config
.
const map: <[[string, number], number], ServiceConfig>(self: Config.Config<[[string, number], number]>, f: (a: [[string, number], number]) => ServiceConfig) => Config.Config<ServiceConfig> (+1 overload)

Returns a config whose structure is the same as this one, but which produces a different value, constructed using the specified function.

@since2.0.0

map
(
import Config
Config
.
const all: <readonly [Config.Config<[string, number]>, Config.Config<number>]>(arg: readonly [Config.Config<[string, number]>, Config.Config<number>]) => Config.Config<[[string, number], number]>

Constructs a config from a tuple / struct / arguments of configs.

@since2.0.0

all
([
// 从'SERVER'命名空间读取'HOST'和'PORT'
import Config
Config
.
const nested: <[string, number]>(self: Config.Config<[string, number]>, name: string) => Config.Config<[string, number]> (+1 overload)

Returns a config that has this configuration nested as a property of the specified name.

@since2.0.0

nested
(
const serverConfig: Config.Config<[string, number]>
serverConfig
, "SERVER"),
// 从根命名空间读取'TIMEOUT'
import Config
Config
.
const number: (name?: string) => Config.Config<number>

Constructs a config for a float value.

@since2.0.0

number
("TIMEOUT")
]),
([[
host: string
host
,
port: number
port
],
timeout: number
timeout
]) => new
constructor ServiceConfig(host: string, port: number, timeout: number): ServiceConfig
ServiceConfig
(
host: string
host
,
port: number
port
,
timeout: number
timeout
)
)

现在,如果您使用此配置设置运行应用程序,它将查找以下环境变量:

  • SERVER_HOST用于主机值
  • SERVER_PORT用于端口值
  • TIMEOUT用于超时值

这种结构化方法使您的配置更有组织,特别是在处理多个服务或复杂应用程序时。

在测试服务时,有时您需要为测试提供特定的配置。为了模拟这种情况,模拟读取这些值的配置后端很有用。

您可以使用ConfigProvider.fromMap构造函数来实现这一点。 此方法允许您从Map<string, string>创建配置提供者,其中映射表示配置数据。 然后,您可以通过调用Effect.withConfigProvider使用此模拟提供者来替代默认提供者。

示例(为测试模拟配置提供者)

import {
import Config
Config
,
import ConfigProvider
ConfigProvider
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
class
class HostPort
HostPort
{
constructor(readonly
HostPort.host: string
host
: string, readonly
HostPort.port: number
port
: number) {}
get
HostPort.url: string
url
() {
return `${this.
HostPort.host: string
host
}:${this.
HostPort.port: number
port
}`
}
}
const
const config: Config.Config<HostPort>
config
=
import Config
Config
.
const map: <[string, number], HostPort>(self: Config.Config<[string, number]>, f: (a: [string, number]) => HostPort) => Config.Config<HostPort> (+1 overload)

Returns a config whose structure is the same as this one, but which produces a different value, constructed using the specified function.

@since2.0.0

map
(
import Config
Config
.
const all: <readonly [Config.Config<string>, Config.Config<number>]>(arg: readonly [Config.Config<string>, Config.Config<number>]) => Config.Config<[string, number]>

Constructs a config from a tuple / struct / arguments of configs.

@since2.0.0

all
([
import Config
Config
.
const string: (name?: string) => Config.Config<string>

Constructs a config for a string value.

@since2.0.0

string
("HOST"),
import Config
Config
.
const number: (name?: string) => Config.Config<number>

Constructs a config for a float value.

@since2.0.0

number
("PORT")]),
([
host: string
host
,
port: number
port
]) => new
constructor HostPort(host: string, port: number): HostPort
HostPort
(
host: string
host
,
port: number
port
)
)
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<HostPort, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<HostPort, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
const
const hostPort: HostPort
hostPort
= yield*
const config: Config.Config<HostPort>
config
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`Application started: ${
const hostPort: HostPort
hostPort
.
HostPort.url: string
url
}`)
})
// 使用包含测试数据的映射创建模拟配置提供者
const
const mockConfigProvider: ConfigProvider.ConfigProvider
mockConfigProvider
=
import ConfigProvider
ConfigProvider
.
const fromMap: (map: Map<string, string>, config?: Partial<ConfigProvider.ConfigProvider.FromMapConfig>) => ConfigProvider.ConfigProvider

Constructs a ConfigProvider using a map and the specified delimiter string, which determines how to split the keys in the map into path segments.

@since2.0.0

fromMap
(
new
var Map: MapConstructor
new <string, string>(iterable?: Iterable<readonly [string, string]> | null | undefined) => Map<string, string> (+3 overloads)
Map
([
["HOST", "localhost"],
["PORT", "8080"]
])
)
// 使用模拟配置提供者运行程序
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const withConfigProvider: <void, ConfigError, never>(self: Effect.Effect<void, ConfigError, never>, provider: ConfigProvider.ConfigProvider) => Effect.Effect<void, ConfigError, never> (+1 overload)

Executes an effect using a specific configuration provider.

Details

This function lets you run an effect with a specified configuration provider. The custom provider will override the default configuration provider for the duration of the effect's execution.

When to Use

This is particularly useful when you need to use a different set of configuration values or sources for specific parts of your application.

Example

import { Config, ConfigProvider, Effect } from "effect"
const customProvider: ConfigProvider.ConfigProvider = ConfigProvider.fromMap(
new Map([["custom-key", "custom-value"]])
)
const program = Effect.withConfigProvider(customProvider)(
Effect.gen(function*() {
const value = yield* Config.string("custom-key")
console.log(`Config value: ${value}`)
})
)
Effect.runPromise(program)
// Output:
// Config value: custom-value

@since2.0.0

withConfigProvider
(
const program: Effect.Effect<void, ConfigError, never>
program
,
const mockConfigProvider: ConfigProvider.ConfigProvider
mockConfigProvider
))
// Output: Application started: localhost:8080

这种方法帮助您创建不依赖外部环境变量的隔离测试,确保您的测试使用模拟配置一致地运行。

对于更复杂的设置,配置通常包括嵌套键。默认情况下,ConfigProvider.fromMap使用.作为嵌套键的分隔符。

示例(提供嵌套配置值)

import {
import Config
Config
,
import ConfigProvider
ConfigProvider
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const config: Config.Config<number>
config
=
import Config
Config
.
const nested: <number>(self: Config.Config<number>, name: string) => Config.Config<number> (+1 overload)

Returns a config that has this configuration nested as a property of the specified name.

@since2.0.0

nested
(
import Config
Config
.
const number: (name?: string) => Config.Config<number>

Constructs a config for a float value.

@since2.0.0

number
("PORT"), "SERVER")
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<number, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<number, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
const
const port: number
port
= yield*
const config: Config.Config<number>
config
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`Server is running on port ${
const port: number
port
}`)
})
// 使用'.'作为嵌套键分隔符的模拟配置
const
const mockConfigProvider: ConfigProvider.ConfigProvider
mockConfigProvider
=
import ConfigProvider
ConfigProvider
.
const fromMap: (map: Map<string, string>, config?: Partial<ConfigProvider.ConfigProvider.FromMapConfig>) => ConfigProvider.ConfigProvider

Constructs a ConfigProvider using a map and the specified delimiter string, which determines how to split the keys in the map into path segments.

@since2.0.0

fromMap
(
new
var Map: MapConstructor
new <string, string>(iterable?: Iterable<readonly [string, string]> | null | undefined) => Map<string, string> (+3 overloads)
Map
([["SERVER.PORT", "8080"]])
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const withConfigProvider: <void, ConfigError, never>(self: Effect.Effect<void, ConfigError, never>, provider: ConfigProvider.ConfigProvider) => Effect.Effect<void, ConfigError, never> (+1 overload)

Executes an effect using a specific configuration provider.

Details

This function lets you run an effect with a specified configuration provider. The custom provider will override the default configuration provider for the duration of the effect's execution.

When to Use

This is particularly useful when you need to use a different set of configuration values or sources for specific parts of your application.

Example

import { Config, ConfigProvider, Effect } from "effect"
const customProvider: ConfigProvider.ConfigProvider = ConfigProvider.fromMap(
new Map([["custom-key", "custom-value"]])
)
const program = Effect.withConfigProvider(customProvider)(
Effect.gen(function*() {
const value = yield* Config.string("custom-key")
console.log(`Config value: ${value}`)
})
)
Effect.runPromise(program)
// Output:
// Config value: custom-value

@since2.0.0

withConfigProvider
(
const program: Effect.Effect<void, ConfigError, never>
program
,
const mockConfigProvider: ConfigProvider.ConfigProvider
mockConfigProvider
))
// Output: Server is running on port 8080

如果您的配置数据使用不同的分隔符(如_),您可以使用ConfigProvider.fromMap中的pathDelim选项更改分隔符。

示例(使用自定义路径分隔符)

import {
import Config
Config
,
import ConfigProvider
ConfigProvider
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const config: Config.Config<number>
config
=
import Config
Config
.
const nested: <number>(self: Config.Config<number>, name: string) => Config.Config<number> (+1 overload)

Returns a config that has this configuration nested as a property of the specified name.

@since2.0.0

nested
(
import Config
Config
.
const number: (name?: string) => Config.Config<number>

Constructs a config for a float value.

@since2.0.0

number
("PORT"), "SERVER")
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<number, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<number, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
const
const port: number
port
= yield*
const config: Config.Config<number>
config
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`Server is running on port ${
const port: number
port
}`)
})
// 使用'_'作为分隔符的模拟配置
const
const mockConfigProvider: ConfigProvider.ConfigProvider
mockConfigProvider
=
import ConfigProvider
ConfigProvider
.
const fromMap: (map: Map<string, string>, config?: Partial<ConfigProvider.ConfigProvider.FromMapConfig>) => ConfigProvider.ConfigProvider

Constructs a ConfigProvider using a map and the specified delimiter string, which determines how to split the keys in the map into path segments.

@since2.0.0

fromMap
(
new
var Map: MapConstructor
new <string, string>(iterable?: Iterable<readonly [string, string]> | null | undefined) => Map<string, string> (+3 overloads)
Map
([["SERVER_PORT", "8080"]]),
{
pathDelim?: string
pathDelim
: "_" }
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const withConfigProvider: <void, ConfigError, never>(self: Effect.Effect<void, ConfigError, never>, provider: ConfigProvider.ConfigProvider) => Effect.Effect<void, ConfigError, never> (+1 overload)

Executes an effect using a specific configuration provider.

Details

This function lets you run an effect with a specified configuration provider. The custom provider will override the default configuration provider for the duration of the effect's execution.

When to Use

This is particularly useful when you need to use a different set of configuration values or sources for specific parts of your application.

Example

import { Config, ConfigProvider, Effect } from "effect"
const customProvider: ConfigProvider.ConfigProvider = ConfigProvider.fromMap(
new Map([["custom-key", "custom-value"]])
)
const program = Effect.withConfigProvider(customProvider)(
Effect.gen(function*() {
const value = yield* Config.string("custom-key")
console.log(`Config value: ${value}`)
})
)
Effect.runPromise(program)
// Output:
// Config value: custom-value

@since2.0.0

withConfigProvider
(
const program: Effect.Effect<void, ConfigError, never>
program
,
const mockConfigProvider: ConfigProvider.ConfigProvider
mockConfigProvider
))
// Output: Server is running on port 8080

Effect中的ConfigProvider模块允许应用程序从不同来源加载配置值。 默认提供者从环境变量读取,但您可以在需要时自定义其行为。

ConfigProvider.fromEnv函数创建一个从环境变量加载值的ConfigProvider。这是Effect使用的默认提供者,除非指定了另一个。

如果您的应用程序需要嵌套配置键的自定义分隔符,您可以相应地配置ConfigProvider.fromEnv

示例(更改路径分隔符)

以下示例修改环境变量的路径分隔符("__")和序列分隔符("|")。

index.ts
import {
import Config
Config
,
import ConfigProvider
ConfigProvider
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<number, ConfigError, never>> | YieldWrap<Effect.Effect<string, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<number, ConfigError, never>> | YieldWrap<Effect.Effect<string, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
// 将SERVER_HOST和SERVER_PORT读取为嵌套配置值
const
const port: number
port
= yield*
import Config
Config
.
const nested: <number>(self: Config.Config<number>, name: string) => Config.Config<number> (+1 overload)

Returns a config that has this configuration nested as a property of the specified name.

@since2.0.0

nested
(
import Config
Config
.
const number: (name?: string) => Config.Config<number>

Constructs a config for a float value.

@since2.0.0

number
("PORT"), "SERVER")
const
const host: string
host
= yield*
import Config
Config
.
const nested: <string>(self: Config.Config<string>, name: string) => Config.Config<string> (+1 overload)

Returns a config that has this configuration nested as a property of the specified name.

@since2.0.0

nested
(
import Config
Config
.
const string: (name?: string) => Config.Config<string>

Constructs a config for a string value.

@since2.0.0

string
("HOST"), "SERVER")
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`Application started: ${
const host: string
host
}:${
const port: number
port
}`)
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const withConfigProvider: <void, ConfigError, never>(self: Effect.Effect<void, ConfigError, never>, provider: ConfigProvider.ConfigProvider) => Effect.Effect<void, ConfigError, never> (+1 overload)

Executes an effect using a specific configuration provider.

Details

This function lets you run an effect with a specified configuration provider. The custom provider will override the default configuration provider for the duration of the effect's execution.

When to Use

This is particularly useful when you need to use a different set of configuration values or sources for specific parts of your application.

Example

import { Config, ConfigProvider, Effect } from "effect"
const customProvider: ConfigProvider.ConfigProvider = ConfigProvider.fromMap(
new Map([["custom-key", "custom-value"]])
)
const program = Effect.withConfigProvider(customProvider)(
Effect.gen(function*() {
const value = yield* Config.string("custom-key")
console.log(`Config value: ${value}`)
})
)
Effect.runPromise(program)
// Output:
// Config value: custom-value

@since2.0.0

withConfigProvider
(
const program: Effect.Effect<void, ConfigError, never>
program
,
// 自定义分隔符
import ConfigProvider
ConfigProvider
.
const fromEnv: (options?: Partial<ConfigProvider.ConfigProvider.FromEnvConfig>) => ConfigProvider.ConfigProvider

A config provider that loads configuration from context variables

Options:

  • pathDelim: The delimiter for the path segments (default: "_").
  • seqDelim: The delimiter for the sequence of values (default: ",").

@since2.0.0

fromEnv
({
pathDelim?: string
pathDelim
: "__",
seqDelim?: string
seqDelim
: "|" })
)
)

要匹配自定义分隔符("__"),请像这样设置环境变量:

Terminal window
SERVER__HOST=localhost SERVER__PORT=8080 npx tsx index.ts

输出:

Terminal window
Application started: localhost:8080

ConfigProvider.fromJson函数创建一个从JSON对象加载值的ConfigProvider

示例(从JSON读取嵌套配置)

import {
import Config
Config
,
import ConfigProvider
ConfigProvider
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<number, ConfigError, never>> | YieldWrap<Effect.Effect<string, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<number, ConfigError, never>> | YieldWrap<Effect.Effect<string, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
// 将SERVER_HOST和SERVER_PORT读取为嵌套配置值
const
const port: number
port
= yield*
import Config
Config
.
const nested: <number>(self: Config.Config<number>, name: string) => Config.Config<number> (+1 overload)

Returns a config that has this configuration nested as a property of the specified name.

@since2.0.0

nested
(
import Config
Config
.
const number: (name?: string) => Config.Config<number>

Constructs a config for a float value.

@since2.0.0

number
("PORT"), "SERVER")
const
const host: string
host
= yield*
import Config
Config
.
const nested: <string>(self: Config.Config<string>, name: string) => Config.Config<string> (+1 overload)

Returns a config that has this configuration nested as a property of the specified name.

@since2.0.0

nested
(
import Config
Config
.
const string: (name?: string) => Config.Config<string>

Constructs a config for a string value.

@since2.0.0

string
("HOST"), "SERVER")
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`Application started: ${
const host: string
host
}:${
const port: number
port
}`)
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const withConfigProvider: <void, ConfigError, never>(self: Effect.Effect<void, ConfigError, never>, provider: ConfigProvider.ConfigProvider) => Effect.Effect<void, ConfigError, never> (+1 overload)

Executes an effect using a specific configuration provider.

Details

This function lets you run an effect with a specified configuration provider. The custom provider will override the default configuration provider for the duration of the effect's execution.

When to Use

This is particularly useful when you need to use a different set of configuration values or sources for specific parts of your application.

Example

import { Config, ConfigProvider, Effect } from "effect"
const customProvider: ConfigProvider.ConfigProvider = ConfigProvider.fromMap(
new Map([["custom-key", "custom-value"]])
)
const program = Effect.withConfigProvider(customProvider)(
Effect.gen(function*() {
const value = yield* Config.string("custom-key")
console.log(`Config value: ${value}`)
})
)
Effect.runPromise(program)
// Output:
// Config value: custom-value

@since2.0.0

withConfigProvider
(
const program: Effect.Effect<void, ConfigError, never>
program
,
import ConfigProvider
ConfigProvider
.
const fromJson: (json: unknown) => ConfigProvider.ConfigProvider

Constructs a new ConfigProvider from a JSON object.

@since2.0.0

fromJson
(
var JSON: JSON

An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.

JSON
.
JSON.parse(text: string, reviver?: (this: any, key: string, value: any) => any): any

Converts a JavaScript Object Notation (JSON) string into an object.

@paramtext A valid JSON string.

@paramreviver A function that transforms the results. This function is called for each member of the object. If a member contains nested objects, the nested objects are transformed before the parent object is.

@throws{SyntaxError} If text is not valid JSON.

parse
(`{"SERVER":{"PORT":8080,"HOST":"localhost"}}`)
)
)
)
// Output: Application started: localhost:8080

ConfigProvider.nested函数允许在命名空间下分组配置值。 这在逻辑上构造设置时很有帮助,例如分组SERVER相关的值。

示例(使用嵌套命名空间)

index.ts
import {
import Config
Config
,
import ConfigProvider
ConfigProvider
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<number, ConfigError, never>> | YieldWrap<Effect.Effect<string, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<number, ConfigError, never>> | YieldWrap<Effect.Effect<string, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
const
const port: number
port
= yield*
import Config
Config
.
const number: (name?: string) => Config.Config<number>

Constructs a config for a float value.

@since2.0.0

number
("PORT") // 读取SERVER_PORT
const
const host: string
host
= yield*
import Config
Config
.
const string: (name?: string) => Config.Config<string>

Constructs a config for a string value.

@since2.0.0

string
("HOST") // 读取SERVER_HOST
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`Application started: ${
const host: string
host
}:${
const port: number
port
}`)
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const withConfigProvider: <void, ConfigError, never>(self: Effect.Effect<void, ConfigError, never>, provider: ConfigProvider.ConfigProvider) => Effect.Effect<void, ConfigError, never> (+1 overload)

Executes an effect using a specific configuration provider.

Details

This function lets you run an effect with a specified configuration provider. The custom provider will override the default configuration provider for the duration of the effect's execution.

When to Use

This is particularly useful when you need to use a different set of configuration values or sources for specific parts of your application.

Example

import { Config, ConfigProvider, Effect } from "effect"
const customProvider: ConfigProvider.ConfigProvider = ConfigProvider.fromMap(
new Map([["custom-key", "custom-value"]])
)
const program = Effect.withConfigProvider(customProvider)(
Effect.gen(function*() {
const value = yield* Config.string("custom-key")
console.log(`Config value: ${value}`)
})
)
Effect.runPromise(program)
// Output:
// Config value: custom-value

@since2.0.0

withConfigProvider
(
const program: Effect.Effect<void, ConfigError, never>
program
,
import ConfigProvider
ConfigProvider
.
const fromEnv: (options?: Partial<ConfigProvider.ConfigProvider.FromEnvConfig>) => ConfigProvider.ConfigProvider

A config provider that loads configuration from context variables

Options:

  • pathDelim: The delimiter for the path segments (default: "_").
  • seqDelim: The delimiter for the sequence of values (default: ",").

@since2.0.0

fromEnv
().
Pipeable.pipe<ConfigProvider.ConfigProvider, ConfigProvider.ConfigProvider>(this: ConfigProvider.ConfigProvider, ab: (_: ConfigProvider.ConfigProvider) => ConfigProvider.ConfigProvider): ConfigProvider.ConfigProvider (+21 overloads)
pipe
(
// 使用SERVER作为命名空间
import ConfigProvider
ConfigProvider
.
const nested: (name: string) => (self: ConfigProvider.ConfigProvider) => ConfigProvider.ConfigProvider (+1 overload)

Returns a new config provider that will automatically nest all configuration under the specified property name. This can be utilized to aggregate separate configuration sources that are all required to load a single configuration value.

@since2.0.0

nested
("SERVER")
)
)
)

由于我们将"SERVER"定义为命名空间,环境变量必须遵循此模式:

Terminal window
SERVER_HOST=localhost SERVER_PORT=8080 npx tsx index.ts

输出:

Terminal window
Application started: localhost:8080

ConfigProvider.constantCase函数将所有配置键转换为常量大小写(带下划线的大写)。 这在调整环境变量以匹配不同命名约定时很有用。

示例(为环境变量使用constantCase

index.ts
import {
import Config
Config
,
import ConfigProvider
ConfigProvider
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<number, ConfigError, never>> | YieldWrap<Effect.Effect<string, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<number, ConfigError, never>> | YieldWrap<Effect.Effect<string, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
const
const port: number
port
= yield*
import Config
Config
.
const number: (name?: string) => Config.Config<number>

Constructs a config for a float value.

@since2.0.0

number
("Port") // 读取PORT
const
const host: string
host
= yield*
import Config
Config
.
const string: (name?: string) => Config.Config<string>

Constructs a config for a string value.

@since2.0.0

string
("Host") // 读取HOST
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`Application started: ${
const host: string
host
}:${
const port: number
port
}`)
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const withConfigProvider: <void, ConfigError, never>(self: Effect.Effect<void, ConfigError, never>, provider: ConfigProvider.ConfigProvider) => Effect.Effect<void, ConfigError, never> (+1 overload)

Executes an effect using a specific configuration provider.

Details

This function lets you run an effect with a specified configuration provider. The custom provider will override the default configuration provider for the duration of the effect's execution.

When to Use

This is particularly useful when you need to use a different set of configuration values or sources for specific parts of your application.

Example

import { Config, ConfigProvider, Effect } from "effect"
const customProvider: ConfigProvider.ConfigProvider = ConfigProvider.fromMap(
new Map([["custom-key", "custom-value"]])
)
const program = Effect.withConfigProvider(customProvider)(
Effect.gen(function*() {
const value = yield* Config.string("custom-key")
console.log(`Config value: ${value}`)
})
)
Effect.runPromise(program)
// Output:
// Config value: custom-value

@since2.0.0

withConfigProvider
(
const program: Effect.Effect<void, ConfigError, never>
program
,
// 将键转换为常量大小写
import ConfigProvider
ConfigProvider
.
const fromEnv: (options?: Partial<ConfigProvider.ConfigProvider.FromEnvConfig>) => ConfigProvider.ConfigProvider

A config provider that loads configuration from context variables

Options:

  • pathDelim: The delimiter for the path segments (default: "_").
  • seqDelim: The delimiter for the sequence of values (default: ",").

@since2.0.0

fromEnv
().
Pipeable.pipe<ConfigProvider.ConfigProvider, ConfigProvider.ConfigProvider>(this: ConfigProvider.ConfigProvider, ab: (_: ConfigProvider.ConfigProvider) => ConfigProvider.ConfigProvider): ConfigProvider.ConfigProvider (+21 overloads)
pipe
(
import ConfigProvider
ConfigProvider
.
const constantCase: (self: ConfigProvider.ConfigProvider) => ConfigProvider.ConfigProvider

Returns a new config provider that will automatically convert all property names to constant case. This can be utilized to adapt the names of configuration properties from the default naming convention of camel case to the naming convention of a config provider.

@since2.0.0

constantCase
)
)
)

由于constantCase"Port""PORT""Host""HOST"转换,环境变量必须按如下设置:

Terminal window
HOST=localhost PORT=8080 npx tsx index.ts

输出:

Terminal window
Application started: localhost:8080

自版本3.3.0起弃用:请使用Config.redacted来处理敏感信息。

Config.secret函数以前用于以类似于Config.redacted的方式保护敏感信息。它将配置值包装在Secret类型中,该类型在记录时也会隐藏详细信息,但允许通过Secret.value访问。

示例(使用已弃用的Config.secret

secret.ts
import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Config
Config
,
import Secret
Secret
} from "effect"
const
const program: Effect.Effect<void, ConfigError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<Secret.Secret, ConfigError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<Secret.Secret, ConfigError, never>>, void, never>) => Effect.Effect<void, ConfigError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
const
const secret: Secret.Secret
secret
= yield*
import Config
Config
.
const secret: (name?: string) => Config.Config<Secret.Secret>

Constructs a config for a secret value.

@since2.0.0

@deprecated

secret
("API_KEY")
// 记录机密值,不会泄露实际机密
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`Console output: ${
const secret: Secret.Secret
secret
}`)
// 使用Secret.value访问真实值并记录它
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(`Actual value: ${
import Secret
Secret
.
const value: (self: Secret.Secret) => string

@since2.0.0

@deprecated

value
(
const secret: Secret.Secret
secret
)}`)
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, ConfigError>(effect: Effect.Effect<void, ConfigError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

runPromise
(
const program: Effect.Effect<void, ConfigError, never>
program
)

当执行此程序时:

Terminal window
API_KEY=my-api-key tsx secret.ts

输出将如下所示:

Terminal window
Console output: Secret(<redacted>)
Actual value: my-api-key