Hyperlinkv0.8.0-beta.28

Schema

Schema.declarefunctioneffect/Schema.ts:409
declare<T, Iso>

Creates a schema for a non-parametric opaque type using a type-guard function. The schema accepts any unknown value and succeeds when is returns true, failing with an InvalidType issue otherwise.

When to use

Use when you are defining a schema for an opaque type with no type parameters and validation can be expressed as a type guard.

Example (Defining a schema for a custom UserId branded type)

import { Schema } from "effect"

type UserId = string & { readonly _tag: "UserId" }

const isUserId = (u: unknown): u is UserId =>
  typeof u === "string" && u.startsWith("user_")

const UserId = Schema.declare<UserId>(isUserId, {
  title: "UserId",
  description: "A user identifier starting with 'user_'"
})
constructorsdeclareConstructor
Source effect/Schema.ts:40948 lines
export interface declare<T, Iso = T> extends declareConstructor<T, T, readonly [], Iso> {
  readonly "Rebuild": declare<T, Iso>
}

/**
 * Creates a schema for a **non-parametric** opaque type using a type-guard
 * function. The schema accepts any unknown value and succeeds when `is` returns
 * `true`, failing with an `InvalidType` issue otherwise.
 *
 * **When to use**
 *
 * Use when you are defining a schema for an opaque type with no type parameters
 * and validation can be expressed as a type guard.
 *
 * **Example** (Defining a schema for a custom `UserId` branded type)
 *
 * ```ts
 * import { Schema } from "effect"
 *
 * type UserId = string & { readonly _tag: "UserId" }
 *
 * const isUserId = (u: unknown): u is UserId =>
 *   typeof u === "string" && u.startsWith("user_")
 *
 * const UserId = Schema.declare<UserId>(isUserId, {
 *   title: "UserId",
 *   description: "A user identifier starting with 'user_'"
 * })
 * ```
 *
 * @see {@link declareConstructor} for creating schemas for parametric types.
 *
 * @category constructors
 * @since 3.10.0
 */
export function declare<T, Iso = T>(
  is: (u: unknown) => u is T,
  annotations?: Annotations.Declaration<T> | undefined
): declare<T, Iso> {
  return declareConstructor<T, T, Iso>()(
    [],
    () => (input, ast) =>
      is(input) ?
        Effect.succeed(input) :
        Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))),
    annotations
  )
}
Referenced by 8 symbols