Pattern matching is a method that allows developers to handle intricate conditions within a single, concise expression. It simplifies code, making it more concise and easier to understand. Additionally, it includes a process called exhaustiveness checking, which helps to ensure that no possible case has been overlooked.
Originating from functional programming languages, pattern matching stands as a powerful technique for code branching. It often offers a more potent and less verbose solution compared to imperative alternatives such as if/else or switch statements, particularly when dealing with complex conditions.
Although not yet a native feature in JavaScript, there’s an ongoing tc39 proposal in its early stages to introduce pattern matching to JavaScript. However, this proposal is at stage 1 and might take several years to be implemented. Nonetheless, developers can implement pattern matching in their codebase. The effect/Match module provides a reliable, type-safe pattern matching implementation that is available for immediate use.
Example (Handling Different Data Types with Pattern Matching)
1
import {
import Match
Match } from"effect"
2
3
// Simulated dynamic input that can be a string or a number
This function allows you to define a Matcher directly from a given value,
rather than from a type. This is useful when working with known values,
enabling structured pattern matching on objects, primitives, or any data
structure.
Once the matcher is created, you can use pattern-matching functions like
when
to define how different cases should be handled.
@see ― type for creating a matcher from a specific type.
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
// Match when age is exactly 18
Match.when({ age: 18 }, () =>"You can vote"),
// Fallback case for all other ages
Match.orElse((user) =>`${user.age} is too young`)
)
console.log(match({ age: 20 }))
// Output: "Age: 20"
console.log(match({ age: 18 }))
// Output: "You can vote"
console.log(match({ age: 4 }))
// Output: "4 is too young"
@since ― 1.0.0
when(
import Match
Match.
conststring:Refinement<unknown, string>
Matches values of type string.
@since ― 1.0.0
string, (
s: string
s) =>`string: ${
s: string
s}`),
13
// Ensure all possible cases are covered
14
import Match
Match.
constexhaustive: <I, F, A, Pr, Ret>(self:Match.Matcher<I, F, never, A, Pr, Ret>) => [Pr] extends [never] ? (u:I) =>Unify<A> :Unify<A>
The Match.exhaustive method finalizes the pattern matching process by
ensuring that all possible cases are accounted for. If any case is missing,
TypeScript will produce a type error. This is particularly useful when
working with unions, as it helps prevent unintended gaps in pattern matching.
@example
// Title: Ensuring All Cases Are Covered
import { Match } from"effect"
// Create a matcher for string or number values
constmatch= Match.type<string|number>().pipe(
// Match when the value is a number
Match.when(Match.number, (n) =>`number: ${n}`),
// Mark the match as exhaustive, ensuring all cases are handled
// TypeScript will throw an error if any case is missing
//
@since ― 1.0.0
exhaustive
15
)
16
17
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
Creating a matcher.
Define a Matcher that operates on either a specific type or value.
Defining patterns.
Use combinators such as Match.when, Match.not, and Match.tag to specify matching conditions.
Completing the match.
Apply a finalizer such as Match.exhaustive, Match.orElse, or Match.option to determine how unmatched cases should be handled.
Creating a matcher
You can create a Matcher using either:
Match.type<T>(): Matches against a specific type.
Match.value(value): Matches against a specific value.
Matching by Type
The Match.type constructor defines a Matcher that operates on a specific type. Once created, you can use patterns like Match.when to define conditions for handling different cases.
Example (Matching Numbers and Strings)
1
import {
import Match
Match } from"effect"
2
3
// Create a matcher for values that are either strings or numbers
This function defines a Matcher that operates on a given type, allowing you
to specify conditions for handling different cases. Once the matcher is
created, you can use pattern-matching functions like
when
to define
how different values should be processed.
@see ― value for creating a matcher from a specific value.
@example
// Title: Matching Numbers and Strings
import { Match } from"effect"
// Create a matcher for values that are either strings or numbers
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
// Match when age is exactly 18
Match.when({ age: 18 }, () =>"You can vote"),
// Fallback case for all other ages
Match.orElse((user) =>`${user.age} is too young`)
)
console.log(match({ age: 20 }))
// Output: "Age: 20"
console.log(match({ age: 18 }))
// Output: "You can vote"
console.log(match({ age: 4 }))
// Output: "4 is too young"
@since ― 1.0.0
when(
import Match
Match.
conststring:Refinement<unknown, string>
Matches values of type string.
@since ― 1.0.0
string, (
s: string
s) =>`string: ${
s: string
s}`),
12
// Ensure all possible cases are handled
13
import Match
Match.
constexhaustive: <I, F, A, Pr, Ret>(self:Match.Matcher<I, F, never, A, Pr, Ret>) => [Pr] extends [never] ? (u:I) =>Unify<A> :Unify<A>
The Match.exhaustive method finalizes the pattern matching process by
ensuring that all possible cases are accounted for. If any case is missing,
TypeScript will produce a type error. This is particularly useful when
working with unions, as it helps prevent unintended gaps in pattern matching.
@example
// Title: Ensuring All Cases Are Covered
import { Match } from"effect"
// Create a matcher for string or number values
constmatch= Match.type<string|number>().pipe(
// Match when the value is a number
Match.when(Match.number, (n) =>`number: ${n}`),
// Mark the match as exhaustive, ensuring all cases are handled
// TypeScript will throw an error if any case is missing
//
@since ― 1.0.0
exhaustive
14
)
15
16
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
Instead of creating a matcher for a type, you can define one directly from a specific value using Match.value.
Example (Matching an Object by Property)
1
import {
import Match
Match } from"effect"
2
3
const
constinput: {
name:string;
age:number;
}
input= {
name: string
name: "John",
age: number
age: 30 }
4
5
// Create a matcher for the specific object
6
const
constresult:string
result=
import Match
Match.
constvalue: <{
name:string;
age:number;
}>(i: {
name:string;
age:number;
}) =>Match.Matcher<{
name:string;
age:number;
}, Match.Types.Without<never>, {
name:string;
age:number;
}, never, {
name:string;
age:number;
}, any>
Creates a matcher from a specific value.
Details
This function allows you to define a Matcher directly from a given value,
rather than from a type. This is useful when working with known values,
enabling structured pattern matching on objects, primitives, or any data
structure.
Once the matcher is created, you can use pattern-matching functions like
when
to define how different cases should be handled.
@see ― type for creating a matcher from a specific type.
}) =>string) => <I, F, A, Pr>(self:Match.Matcher<...>) =>Match.Matcher<...>
Defines a condition for matching values.
Details
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
This function ensures that a matcher always returns a valid result, even if
no defined patterns match. It acts as a default case, similar to the
default clause in a switch statement or the final else in an if-else
chain.
@example
// Title: Providing a Default Value When No Patterns Match
import { Match } from"effect"
// Create a matcher for string or number values
constmatch= Match.type<string|number>().pipe(
// Match when the value is "a"
Match.when("a", () =>"ok"),
// Fallback when no patterns match
Match.orElse(() =>"fallback")
)
console.log(match("a"))
// Output: "ok"
console.log(match("b"))
// Output: "fallback"
@since ― 1.0.0
orElse(() =>"Oh, not John")
14
)
15
16
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
You can use Match.withReturnType<T>() to ensure that all branches return a specific type.
Example (Validating Return Type Consistency)
This example enforces that every matching branch returns a string.
1
import {
import Match
Match } from"effect"
2
3
const
constmatch: (u: {
a:number;
} | {
b:string;
}) =>string
match=
import Match
Match.
consttype: <{
a:number;
} | {
b:string;
}>() =>Match.Matcher<{
a:number;
} | {
b:string;
}, Match.Types.Without<never>, {
a:number;
} | {
b:string;
}, never, never, any>
Creates a matcher for a specific type.
Details
This function defines a Matcher that operates on a given type, allowing you
to specify conditions for handling different cases. Once the matcher is
created, you can use pattern-matching functions like
when
to define
how different values should be processed.
@see ― value for creating a matcher from a specific value.
@example
// Title: Matching Numbers and Strings
import { Match } from"effect"
// Create a matcher for values that are either strings or numbers
constwithReturnType: <string>() => <I, F, R, A, Pr, _>(self:Match.Matcher<I, F, R, A, Pr, _>) => [string] extends [[A] extends [never] ?any:A] ?Match.Matcher<...> :"withReturnType constraint does not extend Result type"
Ensures that all branches of a matcher return a specific type.
Details
This function enforces a consistent return type across all pattern-matching
branches. By specifying a return type, TypeScript will check that every
matching condition produces a value of the expected type.
Important: This function must be the first step in the matcher pipeline.
If used later, TypeScript will not enforce type consistency correctly.
// ❌ Type error: 'number' is not assignable to type 'string'
//
@since ― 1.0.0
withReturnType<string>(),
6
// ❌ Type error: 'number' is not assignable to type 'string'
7
// @ts-expect-error
8
import Match
Match.
constwhen: <{
a:number;
} | {
b:string;
}, {
readonlya:Refinement<unknown, number>;
}, string, (_: {
a:number;
}) =>string>(pattern: {
readonlya:Refinement<unknown, number>;
}, f: (_: {
a:number;
}) =>string) => <I, F, A, Pr>(self:Match.Matcher<...>) =>Match.Matcher<...>
Defines a condition for matching values.
Details
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
// Match when age is exactly 18
Match.when({ age: 18 }, () =>"You can vote"),
// Fallback case for all other ages
Match.orElse((user) =>`${user.age} is too young`)
)
console.log(match({ age: 20 }))
// Output: "Age: 20"
console.log(match({ age: 18 }))
// Output: "You can vote"
console.log(match({ age: 4 }))
// Output: "4 is too young"
@since ― 1.0.0
when({
a: Refinement<unknown, number>
a:
import Match
Match.
constnumber:Refinement<unknown, number>
Matches values of type number.
@since ― 1.0.0
number }, (
_: {
a: number;
}
_) =>
_: {
a: number;
}
_.
a: number
a),
9
// ✅ Correct: returns a string
10
import Match
Match.
constwhen: <{
b:string;
}, {
readonlyb:Refinement<unknown, string>;
}, string, (_: {
b:string;
}) =>string>(pattern: {
readonlyb:Refinement<unknown, string>;
}, f: (_: {
b:string;
}) =>string) => <I, F, A, Pr>(self:Match.Matcher<...>) =>Match.Matcher<...>
Defines a condition for matching values.
Details
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
// Match when age is exactly 18
Match.when({ age: 18 }, () =>"You can vote"),
// Fallback case for all other ages
Match.orElse((user) =>`${user.age} is too young`)
)
console.log(match({ age: 20 }))
// Output: "Age: 20"
console.log(match({ age: 18 }))
// Output: "You can vote"
console.log(match({ age: 4 }))
// Output: "4 is too young"
@since ― 1.0.0
when({
b: Refinement<unknown, string>
b:
import Match
Match.
conststring:Refinement<unknown, string>
Matches values of type string.
@since ― 1.0.0
string }, (
_: {
b: string;
}
_) =>
_: {
b: string;
}
_.
b: string
b),
11
import Match
Match.
constexhaustive: <I, F, A, Pr, Ret>(self:Match.Matcher<I, F, never, A, Pr, Ret>) => [Pr] extends [never] ? (u:I) =>Unify<A> :Unify<A>
The Match.exhaustive method finalizes the pattern matching process by
ensuring that all possible cases are accounted for. If any case is missing,
TypeScript will produce a type error. This is particularly useful when
working with unions, as it helps prevent unintended gaps in pattern matching.
@example
// Title: Ensuring All Cases Are Covered
import { Match } from"effect"
// Create a matcher for string or number values
constmatch= Match.type<string|number>().pipe(
// Match when the value is a number
Match.when(Match.number, (n) =>`number: ${n}`),
// Mark the match as exhaustive, ensuring all cases are handled
// TypeScript will throw an error if any case is missing
//
@since ― 1.0.0
exhaustive
12
)
Defining patterns
when
The Match.when function allows you to define conditions for matching values. It supports both direct value comparisons and predicate functions.
Example (Matching with Values and Predicates)
1
import {
import Match
Match } from"effect"
2
3
// Create a matcher for objects with an "age" property
4
const
constmatch: (input: {
age:number;
}) =>string
match=
import Match
Match.
consttype: <{
age:number;
}>() =>Match.Matcher<{
age:number;
}, Match.Types.Without<never>, {
age:number;
}, never, never, any>
Creates a matcher for a specific type.
Details
This function defines a Matcher that operates on a given type, allowing you
to specify conditions for handling different cases. Once the matcher is
created, you can use pattern-matching functions like
when
to define
how different values should be processed.
@see ― value for creating a matcher from a specific value.
@example
// Title: Matching Numbers and Strings
import { Match } from"effect"
// Create a matcher for values that are either strings or numbers
}) =>string) => <I, F, A, Pr>(self:Match.Matcher<...>) =>Match.Matcher<...>
Defines a condition for matching values.
Details
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
// Match when age is exactly 18
Match.when({ age: 18 }, () =>"You can vote"),
// Fallback case for all other ages
Match.orElse((user) =>`${user.age} is too young`)
)
console.log(match({ age: 20 }))
// Output: "Age: 20"
console.log(match({ age: 18 }))
// Output: "You can vote"
console.log(match({ age: 4 }))
// Output: "4 is too young"
@since ― 1.0.0
when({
age: 18
age: 18 }, () =>"You can vote"),
9
// Fallback case for all other ages
10
import Match
Match.
constorElse: <{
age:number;
}, any, (user: {
age:number;
}) =>string>(f: (user: {
age:number;
}) =>string) => <I, R, A, Pr>(self:Match.Matcher<I, R, {
This function ensures that a matcher always returns a valid result, even if
no defined patterns match. It acts as a default case, similar to the
default clause in a switch statement or the final else in an if-else
chain.
@example
// Title: Providing a Default Value When No Patterns Match
import { Match } from"effect"
// Create a matcher for string or number values
constmatch= Match.type<string|number>().pipe(
// Match when the value is "a"
Match.when("a", () =>"ok"),
// Fallback when no patterns match
Match.orElse(() =>"fallback")
)
console.log(match("a"))
// Output: "ok"
console.log(match("b"))
// Output: "fallback"
@since ― 1.0.0
orElse((
user: {
age: number;
}
user) =>`${
user: {
age: number;
}
user.
age: number
age} is too young`)
11
)
12
13
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
This function defines a Matcher that operates on a given type, allowing you
to specify conditions for handling different cases. Once the matcher is
created, you can use pattern-matching functions like
when
to define
how different values should be processed.
@see ― value for creating a matcher from a specific value.
@example
// Title: Matching Numbers and Strings
import { Match } from"effect"
// Create a matcher for values that are either strings or numbers
Excludes a specific value from matching while allowing all others.
Details
This function is useful when you need to handle all values except one or
more specific cases. Instead of listing all possible matches manually, this
function simplifies the logic by allowing you to specify values to exclude.
Any excluded value will bypass the provided function and continue matching
through other cases.
This function ensures that a matcher always returns a valid result, even if
no defined patterns match. It acts as a default case, similar to the
default clause in a switch statement or the final else in an if-else
chain.
@example
// Title: Providing a Default Value When No Patterns Match
import { Match } from"effect"
// Create a matcher for string or number values
constmatch= Match.type<string|number>().pipe(
// Match when the value is "a"
Match.when("a", () =>"ok"),
// Fallback when no patterns match
Match.orElse(() =>"fallback")
)
console.log(match("a"))
// Output: "ok"
console.log(match("b"))
// Output: "fallback"
@since ― 1.0.0
orElse(() =>"fallback")
9
)
10
11
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
The Match.tag function allows pattern matching based on the _tag field in a Discriminated Union. You can specify multiple tags to match within a single pattern.
This function defines a Matcher that operates on a given type, allowing you
to specify conditions for handling different cases. Once the matcher is
created, you can use pattern-matching functions like
when
to define
how different values should be processed.
@see ― value for creating a matcher from a specific value.
@example
// Title: Matching Numbers and Strings
import { Match } from"effect"
// Create a matcher for values that are either strings or numbers
}) =>string]) => <I, F, A, Pr>(self:Match.Matcher<...>) =>Match.Matcher<...>
The Match.tag function allows pattern matching based on the _tag field in
a Discriminated Union.
You can specify multiple tags to match within a single pattern.
Note
The Match.tag function relies on the convention within the Effect ecosystem
of naming the tag field as "_tag". Ensure that your discriminated unions
follow this naming convention for proper functionality.
}) =>string]) => <I, F, A, Pr>(self:Match.Matcher<...>) =>Match.Matcher<...>
The Match.tag function allows pattern matching based on the _tag field in
a Discriminated Union.
You can specify multiple tags to match within a single pattern.
Note
The Match.tag function relies on the convention within the Effect ecosystem
of naming the tag field as "_tag". Ensure that your discriminated unions
follow this naming convention for proper functionality.
}) =>string]) => <I, F, A, Pr>(self:Match.Matcher<I, F, {
readonly_tag:"cancel";
}, A, Pr, any>) =>Match.Matcher<...>
The Match.tag function allows pattern matching based on the _tag field in
a Discriminated Union.
You can specify multiple tags to match within a single pattern.
Note
The Match.tag function relies on the convention within the Effect ecosystem
of naming the tag field as "_tag". Ensure that your discriminated unions
follow this naming convention for proper functionality.
constexhaustive: <I, F, A, Pr, Ret>(self:Match.Matcher<I, F, never, A, Pr, Ret>) => [Pr] extends [never] ? (u:I) =>Unify<A> :Unify<A>
The Match.exhaustive method finalizes the pattern matching process by
ensuring that all possible cases are accounted for. If any case is missing,
TypeScript will produce a type error. This is particularly useful when
working with unions, as it helps prevent unintended gaps in pattern matching.
@example
// Title: Ensuring All Cases Are Covered
import { Match } from"effect"
// Create a matcher for string or number values
constmatch= Match.type<string|number>().pipe(
// Match when the value is a number
Match.when(Match.number, (n) =>`number: ${n}`),
// Mark the match as exhaustive, ensuring all cases are handled
// TypeScript will throw an error if any case is missing
//
@since ― 1.0.0
exhaustive
18
)
19
20
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
The Match module provides built-in predicates for common types, such as Match.number, Match.string, and Match.boolean. These predicates simplify the process of matching against primitive types.
Example (Using Built-in Predicates for Property Keys)
This function defines a Matcher that operates on a given type, allowing you
to specify conditions for handling different cases. Once the matcher is
created, you can use pattern-matching functions like
when
to define
how different values should be processed.
@see ― value for creating a matcher from a specific value.
@example
// Title: Matching Numbers and Strings
import { Match } from"effect"
// Create a matcher for values that are either strings or numbers
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
// Match when age is exactly 18
Match.when({ age: 18 }, () =>"You can vote"),
// Fallback case for all other ages
Match.orElse((user) =>`${user.age} is too young`)
)
console.log(match({ age: 20 }))
// Output: "Age: 20"
console.log(match({ age: 18 }))
// Output: "You can vote"
console.log(match({ age: 4 }))
// Output: "4 is too young"
@since ― 1.0.0
when(
import Match
Match.
constsymbol:Refinement<unknown, symbol>
Matches values of type symbol.
@since ― 1.0.0
symbol, (
s: symbol
s) =>`Key is a symbol: ${
var String:StringConstructor
(value?:any) => string
Allows manipulation and formatting of text strings and determination and location of substrings within strings.
String(
s: symbol
s)}`),
10
// Ensure all possible cases are handled
11
import Match
Match.
constexhaustive: <I, F, A, Pr, Ret>(self:Match.Matcher<I, F, never, A, Pr, Ret>) => [Pr] extends [never] ? (u:I) =>Unify<A> :Unify<A>
The Match.exhaustive method finalizes the pattern matching process by
ensuring that all possible cases are accounted for. If any case is missing,
TypeScript will produce a type error. This is particularly useful when
working with unions, as it helps prevent unintended gaps in pattern matching.
@example
// Title: Ensuring All Cases Are Covered
import { Match } from"effect"
// Create a matcher for string or number values
constmatch= Match.type<string|number>().pipe(
// Match when the value is a number
Match.when(Match.number, (n) =>`number: ${n}`),
// Mark the match as exhaustive, ensuring all cases are handled
// TypeScript will throw an error if any case is missing
//
@since ― 1.0.0
exhaustive
12
)
13
14
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
@param ― description Description of the new Symbol object.
Symbol("id")))
21
// Output: "Key is a symbol: Symbol(id)"
Predicate
Description
Match.string
Matches values of type string.
Match.nonEmptyString
Matches non-empty strings.
Match.number
Matches values of type number.
Match.boolean
Matches values of type boolean.
Match.bigint
Matches values of type bigint.
Match.symbol
Matches values of type symbol.
Match.date
Matches values that are instances of Date.
Match.record
Matches objects where keys are string or symbol and values are unknown.
Match.null
Matches the value null.
Match.undefined
Matches the value undefined.
Match.defined
Matches any defined (non-null and non-undefined) value.
Match.any
Matches any value without restrictions.
Match.is(...values)
Matches a specific set of literal values (e.g., Match.is("a", 42, true)).
Match.instanceOf(Class)
Matches instances of a given class.
Completing the match
exhaustive
The Match.exhaustive method finalizes the pattern matching process by ensuring that all possible cases are accounted for. If any case is missing, TypeScript will produce a type error. This is particularly useful when working with unions, as it helps prevent unintended gaps in pattern matching.
This function defines a Matcher that operates on a given type, allowing you
to specify conditions for handling different cases. Once the matcher is
created, you can use pattern-matching functions like
when
to define
how different values should be processed.
@see ― value for creating a matcher from a specific value.
@example
// Title: Matching Numbers and Strings
import { Match } from"effect"
// Create a matcher for values that are either strings or numbers
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
// Match when age is exactly 18
Match.when({ age: 18 }, () =>"You can vote"),
// Fallback case for all other ages
Match.orElse((user) =>`${user.age} is too young`)
)
console.log(match({ age: 20 }))
// Output: "Age: 20"
console.log(match({ age: 18 }))
// Output: "You can vote"
console.log(match({ age: 4 }))
// Output: "4 is too young"
@since ― 1.0.0
when(
import Match
Match.
constnumber:Refinement<unknown, number>
Matches values of type number.
@since ― 1.0.0
number, (
n: number
n) =>`number: ${
n: number
n}`),
7
// Mark the match as exhaustive, ensuring all cases are handled
8
// TypeScript will throw an error if any case is missing
9
// @ts-expect-error Type 'string' is not assignable to type 'never'
10
import Match
Match.
constexhaustive: <I, F, A, Pr, Ret>(self:Match.Matcher<I, F, never, A, Pr, Ret>) => [Pr] extends [never] ? (u:I) =>Unify<A> :Unify<A>
The Match.exhaustive method finalizes the pattern matching process by
ensuring that all possible cases are accounted for. If any case is missing,
TypeScript will produce a type error. This is particularly useful when
working with unions, as it helps prevent unintended gaps in pattern matching.
@example
// Title: Ensuring All Cases Are Covered
import { Match } from"effect"
// Create a matcher for string or number values
constmatch= Match.type<string|number>().pipe(
// Match when the value is a number
Match.when(Match.number, (n) =>`number: ${n}`),
// Mark the match as exhaustive, ensuring all cases are handled
// TypeScript will throw an error if any case is missing
//
@since ― 1.0.0
exhaustive
11
)
orElse
The Match.orElse method defines a fallback value to return when no other patterns match. This ensures that the matcher always produces a valid result.
Example (Providing a Default Value When No Patterns Match)
This function defines a Matcher that operates on a given type, allowing you
to specify conditions for handling different cases. Once the matcher is
created, you can use pattern-matching functions like
when
to define
how different values should be processed.
@see ― value for creating a matcher from a specific value.
@example
// Title: Matching Numbers and Strings
import { Match } from"effect"
// Create a matcher for values that are either strings or numbers
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
This function ensures that a matcher always returns a valid result, even if
no defined patterns match. It acts as a default case, similar to the
default clause in a switch statement or the final else in an if-else
chain.
@example
// Title: Providing a Default Value When No Patterns Match
import { Match } from"effect"
// Create a matcher for string or number values
constmatch= Match.type<string|number>().pipe(
// Match when the value is "a"
Match.when("a", () =>"ok"),
// Fallback when no patterns match
Match.orElse(() =>"fallback")
)
console.log(match("a"))
// Output: "ok"
console.log(match("b"))
// Output: "fallback"
@since ― 1.0.0
orElse(() =>"fallback")
9
)
10
11
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
This function defines a Matcher that operates on a given type, allowing you
to specify conditions for handling different cases. Once the matcher is
created, you can use pattern-matching functions like
when
to define
how different values should be processed.
@see ― value for creating a matcher from a specific value.
@example
// Title: Matching Numbers and Strings
import { Match } from"effect"
// Create a matcher for values that are either strings or numbers
}, f: () =>string) => <I, F, A, Pr>(self:Match.Matcher<I, F, User, A, Pr, any>) =>Match.Matcher<...>
Defines a condition for matching values.
Details
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
// Match when age is exactly 18
Match.when({ age: 18 }, () =>"You can vote"),
// Fallback case for all other ages
Match.orElse((user) =>`${user.age} is too young`)
)
console.log(match({ age: 20 }))
// Output: "Age: 20"
console.log(match({ age: 18 }))
// Output: "You can vote"
console.log(match({ age: 4 }))
// Output: "4 is too young"
@since ― 1.0.0
when({
role: "admin"
role: "admin" }, () =>"Has full access"),
8
import Match
Match.
constwhen: <User, {
readonlyrole:"editor";
}, any, () =>string>(pattern: {
readonlyrole:"editor";
}, f: () =>string) => <I, F, A, Pr>(self:Match.Matcher<I, F, User, A, Pr, any>) =>Match.Matcher<...>
Defines a condition for matching values.
Details
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
// Match when age is exactly 18
Match.when({ age: 18 }, () =>"You can vote"),
// Fallback case for all other ages
Match.orElse((user) =>`${user.age} is too young`)
)
console.log(match({ age: 20 }))
// Output: "Age: 20"
console.log(match({ age: 18 }))
// Output: "You can vote"
console.log(match({ age: 4 }))
// Output: "4 is too young"
@since ― 1.0.0
when({
role: "editor"
role: "editor" }, () =>"Can edit content"),
9
import Match
Match.
constoption: <I, F, R, A, Pr, Ret>(self:Match.Matcher<I, F, R, A, Pr, Ret>) => [Pr] extends [never] ? (input:I) =>Option<Unify<A>> :Option<Unify<A>>
Wraps the match result in an Option, representing an optional match.
Details
This function ensures that the result of a matcher is wrapped in an Option,
making it easy to handle cases where no pattern matches. If a match is found,
it returns Some(value), otherwise, it returns None.
This is useful in cases where a missing match is expected and should be
handled explicitly rather than throwing an error or returning a default
value.
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
The Match.either method wraps the result in an Either, providing a structured way to distinguish between matched and unmatched cases. If a match is found, it returns Right(value), otherwise, it returns Left(no match).
This function defines a Matcher that operates on a given type, allowing you
to specify conditions for handling different cases. Once the matcher is
created, you can use pattern-matching functions like
when
to define
how different values should be processed.
@see ― value for creating a matcher from a specific value.
@example
// Title: Matching Numbers and Strings
import { Match } from"effect"
// Create a matcher for values that are either strings or numbers
}, f: () =>string) => <I, F, A, Pr>(self:Match.Matcher<I, F, User, A, Pr, any>) =>Match.Matcher<...>
Defines a condition for matching values.
Details
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
// Match when age is exactly 18
Match.when({ age: 18 }, () =>"You can vote"),
// Fallback case for all other ages
Match.orElse((user) =>`${user.age} is too young`)
)
console.log(match({ age: 20 }))
// Output: "Age: 20"
console.log(match({ age: 18 }))
// Output: "You can vote"
console.log(match({ age: 4 }))
// Output: "4 is too young"
@since ― 1.0.0
when({
role: "admin"
role: "admin" }, () =>"Has full access"),
8
import Match
Match.
constwhen: <User, {
readonlyrole:"editor";
}, any, () =>string>(pattern: {
readonlyrole:"editor";
}, f: () =>string) => <I, F, A, Pr>(self:Match.Matcher<I, F, User, A, Pr, any>) =>Match.Matcher<...>
Defines a condition for matching values.
Details
This function enables pattern matching by checking whether a given value
satisfies a condition. It supports both direct value comparisons and
predicate functions. If the condition is met, the associated function is
executed.
This function is useful when defining matchers that need to check for
specific values or apply logical conditions to determine a match. It works
well with structured objects and primitive types.
@see ― whenOr Use this when multiple patterns should match in a single
condition.
@see ― whenAnd Use this when a value must match all provided patterns.
@see ― orElse Provides a fallback when no patterns match.
@example
// Title: Matching with Values and Predicates
import { Match } from"effect"
// Create a matcher for objects with an "age" property
constmatch= Match.type<{ age:number }>().pipe(
// Match when age is greater than 18
Match.when({ age: (age) => age >18 }, (user) =>`Age: ${user.age}`),
Wraps the match result in an Either, distinguishing matched and unmatched
cases.
Details
This function ensures that the result of a matcher is always wrapped in an
Either, allowing clear differentiation between successful matches
(Right(value)) and cases where no pattern matched (Left(unmatched value)).
This approach is particularly useful when handling optional values or when an
unmatched case should be explicitly handled rather than returning a default
value or throwing an error.
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).
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(newError('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
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=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(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
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()).