You can import the necessary types and functions from the effect/Schema module:
Example (Namespace Import)
Example (Named Import)
Defining a schema
One common way to define a Schema is by utilizing the Struct constructor.
This constructor allows you to create a new schema that outlines an object with specific properties.
Each property in the object is defined by its own schema, which specifies the data type and any validation rules.
Example (Defining a Simple Object Schema)
This Person schema describes an object with a name (string) and age (number) property:
Extracting Inferred Types
Type
Once you’ve defined a schema (Schema<Type, Encoded, Context>), you can extract the inferred type Type in two ways:
Both approaches yield the same result, but using an interface provides benefits such as performance advantages and improved readability.
Encoded
In a Schema<Type, Encoded, Context>, the Encoded type can differ from the Type type, representing the format in which data is encoded. You can extract the Encoded type in two ways:
Using the Schema.Encoded utility
Accessing the Encoded field directly on the schema
Example (Extracting the Encoded Type)
1
import {
import Schema
Schema } from"effect"
2
3
const
constPerson:Schema.Struct<{
name:typeof Schema.String;
age:typeof Schema.NumberFromString;
}>
Person=
import Schema
Schema.
functionStruct<{
name:typeof Schema.String;
age:typeof Schema.NumberFromString;
}>(fields: {
name:typeof Schema.String;
age:typeof Schema.NumberFromString;
}):Schema.Struct<{
name:typeof Schema.String;
age:typeof Schema.NumberFromString;
}> (+1overload)
@since ― 3.10.0
Struct({
4
name: typeof Schema.String
name:
import Schema
Schema.
classString
exportString
@since ― 3.10.0
String,
5
// a schema that decodes a string to a number
6
age: typeof Schema.NumberFromString
age:
import Schema
Schema.
classNumberFromString
This schema transforms a string into a number by parsing the string using the parse function of the effect/Number module.
It returns an error if the value can't be converted (for example when non-numeric characters are provided).
The following special string values are supported: "NaN", "Infinity", "-Infinity".
Both approaches yield the same result, but using an interface provides benefits such as performance advantages and improved readability.
Context
In a Schema<Type, Encoded, Context>, the Context type represents any external data or dependencies that the schema requires to perform encoding or decoding. You can extract the inferred Context type in two ways:
When defining a schema, you may want to create a schema with an opaque type. This is useful when you want to hide the internal structure of the schema and only expose the type of the schema.
Example (Creating an Opaque Schema)
To create a schema with an opaque type, you can use the following technique that re-declares the schema:
In this case, the field "age" is of type string in the Encoded type of the schema and is of type number in the Type type of the schema. Therefore, we need to define two interfaces (PersonEncoded and Person) and use both to redeclare our final schema Person.
Readonly Types by Default
It’s important to note that by default, most constructors exported by
effect/Schema return readonly types.
Example (Readonly Types in a Schema)
For instance, in the Person schema below:
1
import {
import Schema
Schema } from"effect"
2
3
const
constPerson:Schema.Struct<{
name:typeof Schema.String;
age:typeof Schema.Number;
}>
Person=
import Schema
Schema.
functionStruct<{
name:typeof Schema.String;
age:typeof Schema.Number;
}>(fields: {
name:typeof Schema.String;
age:typeof Schema.Number;
}):Schema.Struct<{
name:typeof Schema.String;
age:typeof Schema.Number;
}> (+1overload)
@since ― 3.10.0
Struct({
4
name: typeof Schema.String
name:
import Schema
Schema.
classString
exportString
@since ― 3.10.0
String,
5
age: typeof Schema.Number
age:
import Schema
Schema.
classNumber
exportNumber
@since ― 3.10.0
Number
6
})
the resulting inferred Type would be:
{
readonlyname: string;
readonlyage: number;
}
Decoding
When working with unknown data types in TypeScript, decoding them into a known structure can be challenging. Luckily, effect/Schema provides several functions to help with this process. Let’s explore how to decode unknown values using these functions.
API
Description
decodeUnknownSync
Synchronously decodes a value and throws an error if parsing fails.
The Schema.decodeUnknownSync function is useful when you want to parse a value and immediately throw an error if the parsing fails.
Example (Using decodeUnknownSync for Immediate Decoding)
1
import {
import Schema
Schema } from"effect"
2
3
const
constPerson:Schema.Struct<{
name:typeof Schema.String;
age:typeof Schema.Number;
}>
Person=
import Schema
Schema.
functionStruct<{
name:typeof Schema.String;
age:typeof Schema.Number;
}>(fields: {
name:typeof Schema.String;
age:typeof Schema.Number;
}):Schema.Struct<{
name:typeof Schema.String;
age:typeof Schema.Number;
}> (+1overload)
@since ― 3.10.0
Struct({
4
name: typeof Schema.String
name:
import Schema
Schema.
classString
exportString
@since ― 3.10.0
String,
5
age: typeof Schema.Number
age:
import Schema
Schema.
classNumber
exportNumber
@since ― 3.10.0
Number
6
})
7
8
// Simulate an unknown input
9
const
constinput:unknown
input:unknown= {
name: string
name: "Alice",
age: number
age: 30 }
10
11
// Example of valid input matching the schema
12
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()).
// Example of invalid input that does not match the schema
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()).
ParseError: Expected { readonly name: string; readonly age: number }, actual null
20
*/
decodeUnknownEither
The Schema.decodeUnknownEither function allows you to parse a value and receive the result as an Either, representing success (Right) or failure (Left). This approach lets you handle parsing errors more gracefully without throwing exceptions.
Example (Using Schema.decodeUnknownEither for Error Handling)
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()).
message: 'Expected { readonly name: string; readonly age: number }, actual null'
33
}
34
*/
35
}
decodeUnknown
If your schema involves asynchronous transformations, the Schema.decodeUnknownSync and Schema.decodeUnknownEither functions will not be suitable.
In such cases, you should use the Schema.decodeUnknown function, which returns an Effect.
constdelay: (duration:DurationInput) => <A, E, R>(self:Effect.Effect<A, E, R>) =>Effect.Effect<A, E, R> (+1overload)
Returns an effect that is delayed from this effect by the specified
Duration.
@since ― 2.0.0
delay("10 millis"))
21
})
22
23
// Attempting to use a synchronous decoder on an async schema
24
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()).
'└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work'
34
}
35
}
36
*/
37
38
// Decoding asynchronously with `Schema.decodeUnknown`
39
import Effect
@since ― 2.0.0
@since ― 2.0.0
@since ― 2.0.0
Effect.
construnPromise: <{
readonlyid:number;
readonlyname:string;
readonlyage:number;
}, ParseError>(effect:Effect.Effect<{
readonlyid:number;
readonlyname:string;
readonlyage:number;
}, ParseError, never>, options?: {
readonlysignal?:AbortSignal;
} |undefined) =>Promise<...>
Executes an effect and returns the result as a Promise.
When to Use
Use runPromise when you need to execute an effect and work with the
result using Promise syntax, typically for compatibility with other
promise-based code.
If the effect succeeds, the promise will resolve with the result. If the
effect fails, the promise will reject with an error.
@see ― runPromiseExit for a version that returns an Exit type instead of rejecting.
@example
// Title: Running a Successful Effect as a Promise
Attaches callbacks for the resolution and/or rejection of the Promise.
@param ― onfulfilled The callback to execute when the Promise is resolved.
@param ― onrejected The callback to execute when the Promise is rejected.
@returns ― A Promise for the completion of which ever callback is executed.
then(
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()).
In the code above, the first approach using Schema.decodeUnknownEither results in an error indicating that the transformation cannot be resolved synchronously.
This occurs because Schema.decodeUnknownEither is not designed for async operations.
The second approach, which uses Schema.decodeUnknown, works correctly, allowing you to handle asynchronous transformations and return the expected result.
Encoding
The Schema module provides several encode* functions to encode data according to a schema:
API
Description
encodeSync
Synchronously encodes data and throws an error if encoding fails.
Example (Using Schema.encodeSync for Immediate Encoding)
1
import {
import Schema
Schema } from"effect"
2
3
const
constPerson:Schema.Struct<{
name:typeof Schema.NonEmptyString;
age:typeof Schema.NumberFromString;
}>
Person=
import Schema
Schema.
functionStruct<{
name:typeof Schema.NonEmptyString;
age:typeof Schema.NumberFromString;
}>(fields: {
name:typeof Schema.NonEmptyString;
age:typeof Schema.NumberFromString;
}):Schema.Struct<{
name:typeof Schema.NonEmptyString;
age:typeof Schema.NumberFromString;
}> (+1overload)
@since ― 3.10.0
Struct({
4
// Ensure name is a non-empty string
5
name: typeof Schema.NonEmptyString
name:
import Schema
Schema.
classNonEmptyString
@since ― 3.10.0
NonEmptyString,
6
// Allow age to be decoded from a string and encoded to a string
7
age: typeof Schema.NumberFromString
age:
import Schema
Schema.
classNumberFromString
This schema transforms a string into a number by parsing the string using the parse function of the effect/Number module.
It returns an error if the value can't be converted (for example when non-numeric characters are provided).
The following special string values are supported: "NaN", "Infinity", "-Infinity".
@since ― 3.10.0
NumberFromString
8
})
9
10
// Valid input: encoding succeeds and returns expected types
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()).
// Invalid input: encoding fails due to empty name string
15
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()).
Note that during encoding, the number value 30 was converted to a string "30".
Handling Unsupported Encoding
In certain cases, it may not be feasible to support encoding for a schema. While it is generally advised to define schemas that allow both decoding and encoding, there are situations where encoding a particular type is either unsupported or unnecessary. In these instances, the Forbidden issue can signal that encoding is not available for certain values.
Example (Using Forbidden to Indicate Unsupported Encoding)
Here is an example of a transformation that never fails during decoding. It returns an Either containing either the decoded value or the original input. For encoding, it is reasonable to not support it and use Forbidden as the result.
1
import {
import Either
@since ― 2.0.0
@since ― 2.0.0
Either,
import ParseResult
ParseResult,
import Schema
Schema } from"effect"
2
3
// Define a schema that safely decodes to Either type
4
exportconst
constSafeDecode: <A, I>(self:Schema.Schema<A, I, never>) =>Schema.transformOrFail<typeof Schema.Unknown, Schema.EitherFromSelf<Schema.SchemaClass<A, A, never>, typeof Schema.Unknown>, never>
SafeDecode= <
function (typeparameter) Ain <A, I>(self:Schema.Schema<A, I, never>):Schema.transformOrFail<typeof Schema.Unknown, Schema.EitherFromSelf<Schema.SchemaClass<A, A, never>, typeof Schema.Unknown>, never>
A,
function (typeparameter) Iin <A, I>(self:Schema.Schema<A, I, never>):Schema.transformOrFail<typeof Schema.Unknown, Schema.EitherFromSelf<Schema.SchemaClass<A, A, never>, typeof Schema.Unknown>, never>
I>(
self: Schema.Schema<A, I, never>
self:
import Schema
Schema.
interfaceSchema<inoutA, inoutI=A, outR=never>
@since ― 3.10.0
@since ― 3.10.0
Schema<
function (typeparameter) Ain <A, I>(self:Schema.Schema<A, I, never>):Schema.transformOrFail<typeof Schema.Unknown, Schema.EitherFromSelf<Schema.SchemaClass<A, A, never>, typeof Schema.Unknown>, never>
A,
function (typeparameter) Iin <A, I>(self:Schema.Schema<A, I, never>):Schema.transformOrFail<typeof Schema.Unknown, Schema.EitherFromSelf<Schema.SchemaClass<A, A, never>, typeof Schema.Unknown>, never>
Create a new Schema by transforming the input and output of an existing Schema
using the provided decoding functions.
@since ― 3.10.0
transformOrFail(
7
import Schema
Schema.
classUnknown
@since ― 3.10.0
Unknown,
8
import Schema
Schema.
constEitherFromSelf: <Schema.SchemaClass<A, A, never>, typeof Schema.Unknown>({ left, right }: {
readonlyleft:typeof Schema.Unknown;
readonlyright:Schema.SchemaClass<A, A, never>;
}) =>Schema.EitherFromSelf<...>
@since ― 3.10.0
EitherFromSelf({
9
left: typeof Schema.Unknown
left:
import Schema
Schema.
classUnknown
@since ― 3.10.0
Unknown,
10
right: Schema.SchemaClass<A, A, never>
right:
import Schema
Schema.
consttypeSchema: <A, I, never>(schema:Schema.Schema<A, I, never>) =>Schema.SchemaClass<A, A, never>
The typeSchema function allows you to extract the Type portion of a
schema, creating a new schema that conforms to the properties defined in the
original schema without considering the initial encoding or transformation
processes.
@since ― 3.10.0
typeSchema(
self: Schema.Schema<A, I, never>
self)
11
}),
12
{
13
strict?:true
strict: true,
14
// Decode: map a failed result to the input as Left,
Takes two functions and an Either value, if the value is a Left the inner value is applied to the onLeft function, if the value is a Rightthe inner value is applied to theonRight` function.
The Forbidden variant of the ParseIssue type represents a forbidden operation, such as when encountering an Effect that is not allowed to execute (e.g., using runSync).
Decoding: The SafeDecode function ensures that decoding never fails. It wraps the decoded value in an Either, where a successful decoding results in a Right and a failed decoding results in a Left containing the original input.
Encoding: The encoding process uses the Forbidden error to indicate that encoding a Left value is not supported. Only Right values are successfully encoded.
ParseError
The Schema.decodeUnknownEither and Schema.encodeEither functions returns a Either:
Either<Type, ParseError>
where ParseError is defined as follows (simplified):
interfaceParseError {
readonly_tag:"ParseError"
readonlyissue:ParseIssue
}
In this structure, ParseIssue represents an error that might occur during the parsing process.
It is wrapped in a tagged error to make it easier to catch errors using Effect.catchTag.
The result Either<Type, ParseError> contains the inferred data type described by the schema (Type).
A successful parse yields a Right value with the parsed data Type, while a failed parse results in a Left value containing a ParseError.
Parse Options
The options below provide control over both decoding and encoding behaviors.
Managing Excess properties
By default, any properties not defined in the schema are removed from the output when parsing a value. This ensures the parsed data conforms strictly to the expected structure.
If you want to detect and handle unexpected properties, use the onExcessProperty option (default value: "ignore"), which allows you to raise an error for excess properties. This can be helpful when you need to validate and catch unanticipated properties.
Example (Setting onExcessProperty to "error")
1
import {
import Schema
Schema } from"effect"
2
3
const
constPerson:Schema.Struct<{
name:typeof Schema.String;
age:typeof Schema.Number;
}>
Person=
import Schema
Schema.
functionStruct<{
name:typeof Schema.String;
age:typeof Schema.Number;
}>(fields: {
name:typeof Schema.String;
age:typeof Schema.Number;
}):Schema.Struct<{
name:typeof Schema.String;
age:typeof Schema.Number;
}> (+1overload)
@since ― 3.10.0
Struct({
4
name: typeof Schema.String
name:
import Schema
Schema.
classString
exportString
@since ― 3.10.0
String,
5
age: typeof Schema.Number
age:
import Schema
Schema.
classNumber
exportNumber
@since ― 3.10.0
Number
6
})
7
8
// Excess properties are ignored by default
9
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()).
When using a Schema to parse a value, by default any properties that are
not specified in the Schema will be stripped out from the output. This is
because the Schema is expecting a specific shape for the parsed value,
and any excess properties do not conform to that shape.
However, you can use the onExcessProperty option (default value:
"ignore") to trigger a parsing error. This can be particularly useful in
cases where you need to detect and handle potential errors or unexpected
values.
If you want to allow excess properties to remain, you can use
onExcessProperty set to "preserve".
default: "ignore"
@since ― 3.10.0
onExcessProperty: "error" }
30
)
31
/*
32
throws
33
ParseError: { readonly name: string; readonly age: number }
34
└─ ["email"]
35
└─ is unexpected, expected: "name" | "age"
36
*/
To retain extra properties, set onExcessProperty to "preserve".
Example (Setting onExcessProperty to "preserve")
1
import {
import Schema
Schema } from"effect"
2
3
const
constPerson:Schema.Struct<{
name:typeof Schema.String;
age:typeof Schema.Number;
}>
Person=
import Schema
Schema.
functionStruct<{
name:typeof Schema.String;
age:typeof Schema.Number;
}>(fields: {
name:typeof Schema.String;
age:typeof Schema.Number;
}):Schema.Struct<{
name:typeof Schema.String;
age:typeof Schema.Number;
}> (+1overload)
@since ― 3.10.0
Struct({
4
name: typeof Schema.String
name:
import Schema
Schema.
classString
exportString
@since ― 3.10.0
String,
5
age: typeof Schema.Number
age:
import Schema
Schema.
classNumber
exportNumber
@since ― 3.10.0
Number
6
})
7
8
// Excess properties are preserved in the output
9
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()).
When using a Schema to parse a value, by default any properties that are
not specified in the Schema will be stripped out from the output. This is
because the Schema is expecting a specific shape for the parsed value,
and any excess properties do not conform to that shape.
However, you can use the onExcessProperty option (default value:
"ignore") to trigger a parsing error. This can be particularly useful in
cases where you need to detect and handle potential errors or unexpected
values.
If you want to allow excess properties to remain, you can use
onExcessProperty set to "preserve".
The errors option enables you to retrieve all errors encountered during parsing. By default, only the first error is returned. Setting errors to "all" provides comprehensive error feedback, which can be useful for debugging or offering detailed validation feedback.
Example (Setting errors to "all")
1
import {
import Schema
Schema } from"effect"
2
3
const
constPerson:Schema.Struct<{
name:typeof Schema.String;
age:typeof Schema.Number;
}>
Person=
import Schema
Schema.
functionStruct<{
name:typeof Schema.String;
age:typeof Schema.Number;
}>(fields: {
name:typeof Schema.String;
age:typeof Schema.Number;
}):Schema.Struct<{
name:typeof Schema.String;
age:typeof Schema.Number;
}> (+1overload)
@since ― 3.10.0
Struct({
4
name: typeof Schema.String
name:
import Schema
Schema.
classString
exportString
@since ― 3.10.0
String,
5
age: typeof Schema.Number
age:
import Schema
Schema.
classNumber
exportNumber
@since ― 3.10.0
Number
6
})
7
8
// Attempt to parse with multiple issues in the input data
The errors option allows you to receive all parsing errors when
attempting to parse a value using a schema. By default only the first error
is returned, but by setting the errors option to "all", you can receive
all errors that occurred during the parsing process. This can be useful for
debugging or for providing more comprehensive error messages to the user.
When using a Schema to parse a value, by default any properties that are
not specified in the Schema will be stripped out from the output. This is
because the Schema is expecting a specific shape for the parsed value,
and any excess properties do not conform to that shape.
However, you can use the onExcessProperty option (default value:
"ignore") to trigger a parsing error. This can be particularly useful in
cases where you need to detect and handle potential errors or unexpected
values.
If you want to allow excess properties to remain, you can use
onExcessProperty set to "preserve".
default: "ignore"
@since ― 3.10.0
onExcessProperty: "error" }
16
)
17
/*
18
throws
19
ParseError: { readonly name: string; readonly age: number }
20
├─ ["email"]
21
│ └─ is unexpected, expected: "name" | "age"
22
└─ ["age"]
23
└─ Expected number, actual "abc"
24
*/
Managing Property Order
The propertyOrder option provides control over the order of object fields in the output. This feature is particularly useful when the sequence of keys is important for the consuming processes or when maintaining the input order enhances readability and usability.
By default, the propertyOrder option is set to "none". This means that the internal system decides the order of keys to optimize parsing speed.
The order of keys in this mode should not be considered stable, and it’s recommended not to rely on key ordering as it may change in future updates.
Setting propertyOrder to "original" ensures that the keys are ordered as they appear in the input during the decoding/encoding process.
// Default decoding, where property order is system-defined
10
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 propertyOrder option provides control over the order of object fields
in the output. This feature is particularly useful when the sequence of
keys is important for the consuming processes or when maintaining the input
order enhances readability and usability.
By default, the propertyOrder option is set to "none". This means that
the internal system decides the order of keys to optimize parsing speed.
The order of keys in this mode should not be considered stable, and it's
recommended not to rely on key ordering as it may change in future updates
without notice.
Setting propertyOrder to "original" ensures that the keys are ordered
as they appear in the input during the decoding/encoding process.
Use andThen when you need to run multiple actions in sequence, with the
second action depending on the result of the first. This is useful for
combining effects or handling computations that must happen in order.
Details
The second action can be:
A constant value (similar to
as
)
A function returning a value (similar to
map
)
A Promise
A function returning a Promise
An Effect
A function returning an Effect (similar to
flatMap
)
Note:andThen works well with both Option and Either types,
treating them as effects.
@example
// Title: Applying a Discount Based on Fetched Amount
import { pipe, Effect } from"effect"
// Function to apply a discount safely to a transaction amount
constapplyDiscount= (
total:number,
discountRate:number
):Effect.Effect<number, Error> =>
discountRate ===0
? Effect.fail(newError("Discount rate cannot be zero"))
construnPromise: <A, E>(effect:Effect.Effect<A, E, never>, options?: {
readonlysignal?:AbortSignal;
} |undefined) =>Promise<A>
Executes an effect and returns the result as a Promise.
When to Use
Use runPromise when you need to execute an effect and work with the
result using Promise syntax, typically for compatibility with other
promise-based code.
If the effect succeeds, the promise will resolve with the result. If the
effect fails, the promise will reject with an error.
@see ― runPromiseExit for a version that returns an Exit type instead of rejecting.
@example
// Title: Running a Successful Effect as a Promise
Attaches callbacks for the resolution and/or rejection of the Promise.
@param ― onfulfilled The callback to execute when the Promise is resolved.
@param ― onrejected The callback to execute when the Promise is rejected.
@returns ― A Promise for the completion of which ever callback is executed.
then(
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 propertyOrder option provides control over the order of object fields
in the output. This feature is particularly useful when the sequence of
keys is important for the consuming processes or when maintaining the input
order enhances readability and usability.
By default, the propertyOrder option is set to "none". This means that
the internal system decides the order of keys to optimize parsing speed.
The order of keys in this mode should not be considered stable, and it's
recommended not to rely on key ordering as it may change in future updates
without notice.
Setting propertyOrder to "original" ensures that the keys are ordered
as they appear in the input during the decoding/encoding process.
construnPromise: <A, E>(effect:Effect.Effect<A, E, never>, options?: {
readonlysignal?:AbortSignal;
} |undefined) =>Promise<A>
Executes an effect and returns the result as a Promise.
When to Use
Use runPromise when you need to execute an effect and work with the
result using Promise syntax, typically for compatibility with other
promise-based code.
If the effect succeeds, the promise will resolve with the result. If the
effect fails, the promise will reject with an error.
@see ― runPromiseExit for a version that returns an Exit type instead of rejecting.
@example
// Title: Running a Successful Effect as a Promise
Attaches callbacks for the resolution and/or rejection of the Promise.
@param ― onfulfilled The callback to execute when the Promise is resolved.
@param ― onrejected The callback to execute when the Promise is rejected.
@returns ― A Promise for the completion of which ever callback is executed.
then(
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 parseOptions annotation allows you to customize parsing behavior at different schema levels, enabling you to apply unique parsing settings to nested schemas within a structure. Options defined within a schema override parent-level settings and apply to all nested schemas.
Example (Using parseOptions to Customize Error Handling)
The errors option allows you to receive all parsing errors when
attempting to parse a value using a schema. By default only the first error
is returned, but by setting the errors option to "all", you can receive
all errors that occurred during the parsing process. This can be useful for
debugging or for providing more comprehensive error messages to the user.
The errors option allows you to receive all parsing errors when
attempting to parse a value using a schema. By default only the first error
is returned, but by setting the errors option to "all", you can receive
all errors that occurred during the parsing process. This can be useful for
debugging or for providing more comprehensive error messages to the user.
default: "first"
@since ― 3.10.0
errors: "all" }
18
})
19
20
// Decode input with custom error-handling behavior
The errors option allows you to receive all parsing errors when
attempting to parse a value using a schema. By default only the first error
is returned, but by setting the errors option to "all", you can receive
all errors that occurred during the parsing process. This can be useful for
debugging or for providing more comprehensive error messages to the user.
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 main schema is configured to display all errors. Hence, you will see errors related to both the d field (since it’s missing) and any errors from the a subschema.
The subschema (a) is set to display only the first error. Although both b and c fields are missing, only the first missing field (b) is reported.
Type Guards
The Schema.is function provides a way to verify if a value conforms to a given schema. It acts as a type guard, taking a value of type unknown and determining if it matches the structure and type constraints defined in the schema.
Here’s how the Schema.is function works:
Schema Definition: Define a schema to describe the structure and constraints of the data type you expect. For instance, Schema<Type, Encoded, Context>, where Type is the target type you want to validate against.
Type Guard Creation: Use the schema to create a user-defined type guard, (u: unknown) => u is Type. This function can be used at runtime to check if a value meets the requirements of the schema.
}, never>, options?:ParseOptions): (u:unknown, overrideOptions?:ParseOptions|number) => u is {
readonly name: string;
readonly age: number;
}
export is
By default the option exact is set to true.
@since ― 3.10.0
is(
constPerson:Schema.Struct<{
name:typeof Schema.String;
age:typeof Schema.Number;
}>
Person)
11
12
// Test the type guard with various inputs
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()).
The generated isPerson function has the following signature:
constisPerson: (
u:unknown,
overrideOptions?:number|ParseOptions
) =>uis {
readonlyname:string
readonlyage:number
}
Assertions
While type guards verify whether a value conforms to a specific type, the Schema.asserts function goes further by asserting that an input matches the schema type Type (from Schema<Type, Encoded, Context>).
If the input does not match the schema, it throws a detailed error, making it useful for runtime validation.
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 stderr 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()).
constcode=5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
If formatting elements (e.g. %d) are not found in the first string then
util.inspect() is called on each argument and the
resulting string values are concatenated. See util.format()
for more information.
@since ― v0.1.100
error("The input does not match the schema:")
18
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 stderr 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()).
constcode=5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
If formatting elements (e.g. %d) are not found in the first string then
util.inspect() is called on each argument and the
resulting string values are concatenated. See util.format()
for more information.
@since ― v0.1.100
error(
var e:unknown
e)
19
}
20
/*
21
throws:
22
The input does not match the schema:
23
{
24
_id: 'ParseError',
25
message: '{ readonly name: string; readonly age: number }\n' +
26
'└─ ["age"]\n' +
27
' └─ Expected number, actual "30"'
28
}
29
*/
30
31
// This input matches the schema and will not throw an error
The assertsPerson function generated from the schema has the following signature:
constassertsPerson: (
input:unknown,
overrideOptions?:number|ParseOptions
) =>assertsinputis {
readonlyname:string
readonlyage:number
}
Managing Missing Properties
When decoding, it’s important to understand how missing properties are processed. By default, if a property is not present in the input, it is treated as if it were present with an undefined value.
Example (Default Behavior of Missing Properties)
1
import {
import Schema
Schema } from"effect"
2
3
const
constschema:Schema.Struct<{
a:typeof Schema.Unknown;
}>
schema=
import Schema
Schema.
functionStruct<{
a:typeof Schema.Unknown;
}>(fields: {
a:typeof Schema.Unknown;
}):Schema.Struct<{
a:typeof Schema.Unknown;
}> (+1overload)
@since ― 3.10.0
Struct({
a: typeof Schema.Unknown
a:
import Schema
Schema.
classUnknown
@since ― 3.10.0
Unknown })
4
const
constinput: {}
input= {}
5
6
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()).
In this example, although the key "a" is not present in the input, it is treated as { a: undefined } by default.
If you need your validation logic to differentiate between genuinely missing properties and those explicitly set to undefined, you can enable the exact option.
Example (Setting exact: true to Distinguish Missing Properties)
1
import {
import Schema
Schema } from"effect"
2
3
const
constschema:Schema.Struct<{
a:typeof Schema.Unknown;
}>
schema=
import Schema
Schema.
functionStruct<{
a:typeof Schema.Unknown;
}>(fields: {
a:typeof Schema.Unknown;
}):Schema.Struct<{
a:typeof Schema.Unknown;
}> (+1overload)
@since ― 3.10.0
Struct({
a: typeof Schema.Unknown
a:
import Schema
Schema.
classUnknown
@since ― 3.10.0
Unknown })
4
const
constinput: {}
input= {}
5
6
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()).
Handles missing properties in data structures. By default, missing
properties are treated as if present with an undefined value. To treat
missing properties as errors, set the exact option to true. This
setting is already enabled by default for is and asserts functions,
treating absent properties strictly unless overridden.
default: false
@since ― 3.10.0
exact: true }))
7
/*
8
throws
9
ParseError: { readonly a: unknown }
10
└─ ["a"]
11
└─ is missing
12
*/
For the APIs Schema.is and Schema.asserts, however, the default behavior is to treat missing properties strictly, where the default for exact is true:
Example (Strict Handling of Missing Properties with Schema.is and Schema.asserts)
1
importtype {
import SchemaAST
SchemaAST } from"effect"
2
import {
import Schema
Schema } from"effect"
3
4
const
constschema:Schema.Struct<{
a:typeof Schema.Unknown;
}>
schema=
import Schema
Schema.
functionStruct<{
a:typeof Schema.Unknown;
}>(fields: {
a:typeof Schema.Unknown;
}):Schema.Struct<{
a:typeof Schema.Unknown;
}> (+1overload)
@since ― 3.10.0
Struct({
a: typeof Schema.Unknown
a:
import Schema
Schema.
classUnknown
@since ― 3.10.0
Unknown })
5
const
constinput: {}
input= {}
6
7
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()).
}, never>, options?:SchemaAST.ParseOptions): (u:unknown, overrideOptions?:SchemaAST.ParseOptions|number) => u is {
readonly a: unknown;
}
export is
By default the option exact is set to true.
@since ― 3.10.0
is(
constschema:Schema.Struct<{
a:typeof Schema.Unknown;
}>
schema)(
constinput: {}
input))
8
// Output: false
9
10
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()).
}, never>, options?:SchemaAST.ParseOptions): (u:unknown, overrideOptions?:SchemaAST.ParseOptions|number) => u is {
readonly a: unknown;
}
export is
By default the option exact is set to true.
@since ― 3.10.0
is(
constschema:Schema.Struct<{
a:typeof Schema.Unknown;
}>
schema)(
constinput: {}
input, {
ParseOptions.exact?: boolean |undefined
Handles missing properties in data structures. By default, missing
properties are treated as if present with an undefined value. To treat
missing properties as errors, set the exact option to true. This
setting is already enabled by default for is and asserts functions,
treating absent properties strictly unless overridden.
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 stderr 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()).
constcode=5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
If formatting elements (e.g. %d) are not found in the first string then
util.inspect() is called on each argument and the
resulting string values are concatenated. See util.format()
for more information.
@since ― v0.1.100
error("asserts failed")
25
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 stderr 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()).
constcode=5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
If formatting elements (e.g. %d) are not found in the first string then
util.inspect() is called on each argument and the
resulting string values are concatenated. See util.format()
for more information.
Handles missing properties in data structures. By default, missing
properties are treated as if present with an undefined value. To treat
missing properties as errors, set the exact option to true. This
setting is already enabled by default for is and asserts functions,
treating absent properties strictly unless overridden.
default: false
@since ― 3.10.0
exact: false })
37
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 stderr 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()).
constcode=5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
If formatting elements (e.g. %d) are not found in the first string then
util.inspect() is called on each argument and the
resulting string values are concatenated. See util.format()
for more information.
@since ― v0.1.100
error("asserts failed")
40
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 stderr 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()).
constcode=5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
If formatting elements (e.g. %d) are not found in the first string then
util.inspect() is called on each argument and the
resulting string values are concatenated. See util.format()
for more information.
@since ― v0.1.100
error(
var e:any
e.
any
message)
41
}
42
// Output: asserts passed
Naming Conventions
The naming conventions in effect/Schema are designed to be straightforward and logical, focusing primarily on compatibility with JSON serialization. This approach simplifies the understanding and use of schemas, especially for developers who are integrating web technologies where JSON is a standard data interchange format.
Overview of Naming Strategies
JSON-Compatible Types
Schemas that naturally serialize to JSON-compatible formats are named directly after their data types.
For instance:
Schema.Date: serializes JavaScript Date objects to ISO-formatted strings, a typical method for representing dates in JSON.
Schema.Number: used directly as it maps precisely to the JSON number type, requiring no special transformation to remain JSON-compatible.
Non-JSON-Compatible Types
When dealing with types that do not have a direct representation in JSON, the naming strategy incorporates additional details to indicate the necessary transformation. This helps in setting clear expectations about the schema’s behavior:
For instance:
Schema.DateFromSelf: indicates that the schema handles Date objects, which are not natively JSON-serializable.
Schema.NumberFromString: this naming suggests that the schema processes numbers that are initially represented as strings, emphasizing the transformation from string to number when decoding.
The primary goal of these schemas is to ensure that domain objects can be easily serialized (“encoded”) and deserialized (“decoded”) for transmission over network connections, thus facilitating their transfer between different parts of an application or across different applications.
Rationale
While JSON’s ubiquity justifies its primary consideration in naming, the conventions also accommodate serialization for other types of transport. For instance, converting a Date to a string is a universally useful method for various communication protocols, not just JSON. Thus, the selected naming conventions serve as sensible defaults that prioritize clarity and ease of use, facilitating the serialization and deserialization processes across diverse technological environments.