) => Matcher<
I,
Types.AddWithout>>,
Types.ApplyFilters>>>,
A | ReturnType,
Pr,
Ret
> = internal.literals
/**
* Matches string and number literal values and requires handling of all
* remaining cases.
*
* **Details**
*
* This is the exhaustive variant of {@link literals}. Every remaining member
* must be a finite string or number literal with a corresponding handler, so a
* missing literal, a widened `string` / `number` type, or any other unhandled
* member is reported by TypeScript.
*
* **Example** (Handling all literal cases)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* type Status = "draft" | "review" | "published"
*
* const label = Match.type().pipe(
* Match.literalsExhaustive({
* draft: () => "Draft",
* review: () => "In review",
* published: () => "Live"
* })
* )
*
* label("review") // => "In review"
* ```
*
* @see {@link literals} for defining literal handlers without finalizing the matcher
*
* @stability unstable
* @category defining patterns
* @since 4.1.0
*/
export const literalsExhaustive: <
R,
Ret,
P extends
& LiteralHandlers
& { readonly [K in Exclude>]: never }
>(
fields: Contextual>
) => (
self: Matcher
) => [Pr] extends [never] ? (u: I) => Unify> : Unify> =
internal.literalsExhaustive
/**
* Creates a pattern that excludes a specific value while allowing all others.
*
* **When to use**
*
* Use to add a negative pattern case for inputs that should match when another
* pattern does not.
*
* **Details**
*
* Any excluded value bypasses the provided function and continues matching
* through later cases.
* Object patterns, including nested patterns, use only own enumerable string
* and symbol properties. Non-enumerable and inherited pattern properties are
* ignored. Selected properties on the input may be non-enumerable or inherited.
*
* **Example** (Ignoring a specific value)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* // Create a matcher for string or number values
* const match = Match.type().pipe(
* // Match any value except "hi", returning "ok"
* Match.not("hi", () => "ok"),
* // Fallback case for when the value is "hi"
* Match.orElse(() => "fallback")
* )
*
* match("hello") // => "ok"
*
* match("hi") // => "fallback"
* ```
*
* @see {@link when} for adding a positive pattern case
*
* @stability stable
* @category defining patterns
* @since 4.0.0
*/
export const not: <
R,
const P extends ExactPattern,
Ret,
Args extends Array,
Fn extends (_: Types.NotMatch, ...args: Args) => Ret
>(
pattern: P,
f: Fn
) => (
self: Matcher
) => Matcher<
I,
Types.AddOnly>,
Types.ApplyFilters>>,
A | ReturnType,
Pr,
Ret,
Args
> = internal.not
/**
* Matches non-empty strings.
*
* **When to use**
*
* Use to match strings whose length is greater than zero.
*
* **Details**
*
* This predicate matches any string that contains at least one character,
* effectively filtering out empty strings ("").
*
* **Example** (Matching non-empty strings)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* const processInput = Match.type()
* .pipe(
* Match.when(Match.nonEmptyString, (str) => `Valid input: ${str}`),
* Match.orElse(() => "Input cannot be empty")
* )
*
* processInput("hello") // => "Valid input: hello"
*
* processInput("") // => "Input cannot be empty"
*
* processInput(" ") // => "Valid input: "
* ```
*
* @see {@link string} for matching any string
*
* @stability stable
* @category guards
* @since 4.0.0
*/
export const nonEmptyString: SafeRefinement = internal.nonEmptyString
/**
* Matches a specific set of literal values (e.g., `Match.is("a", 42, true)`).
*
* **When to use**
*
* Use to match one of several literal primitive or null values.
*
* **Details**
*
* This function creates a predicate that matches any of the provided literal values.
* It's useful for matching against multiple specific values in a single pattern.
*
* **Example** (Matching literal values)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* const handleStatus = Match.type()
* .pipe(
* Match.when(Match.is("success", "ok", 200), () => "Operation successful"),
* Match.when(Match.is("error", "failed", 500), () => "Operation failed"),
* Match.when(Match.is(0, false, null), () => "Falsy value"),
* Match.orElse((value) => `Unknown status: ${value}`)
* )
*
* handleStatus("success") // => "Operation successful"
*
* handleStatus(200) // => "Operation successful"
*
* handleStatus("failed") // => "Operation failed"
*
* handleStatus(0) // => "Falsy value"
*
* handleStatus("pending") // => "Unknown status: pending"
* ```
*
* @stability stable
* @category guards
* @since 4.0.0
*/
export const is: <
Literals extends ReadonlyArray
>(...literals: Literals) => SafeRefinement = internal.is
/**
* Matches values of type `string`.
*
* **Details**
*
* This predicate refines unknown values to strings, allowing pattern matching
* on string types. It's commonly used in type-based matchers to handle string cases.
*
* **Example** (Matching string values)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* const processValue = Match.type().pipe(
* Match.when(Match.string, (str) => `String: ${str.toUpperCase()}`),
* Match.when(Match.number, (num) => `Number: ${num * 2}`),
* Match.when(Match.boolean, (bool) => `Boolean: ${bool ? "yes" : "no"}`),
* Match.exhaustive
* )
*
* processValue("hello") // => "String: HELLO"
* processValue(42) // => "Number: 84"
* processValue(true) // => "Boolean: yes"
* ```
*
* @stability stable
* @category guards
* @since 4.0.0
*/
export const string: Predicate.Refinement = Predicate.isString
/**
* Matches values of type `number`.
*
* **When to use**
*
* Use to match primitive number values, including `NaN` and infinities.
*
* **Details**
*
* This predicate refines unknown values to numbers, allowing pattern matching
* on numeric types. It matches all number values including integers, floats,
* `Infinity`, `-Infinity`, and `NaN`.
*
* **Example** (Matching number values)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* const categorizeNumber = Match.type().pipe(
* Match.when(Match.number, (num) => {
* if (Number.isNaN(num)) return "Not a number"
* if (!Number.isFinite(num)) return "Infinite"
* if (Number.isInteger(num)) return `Integer: ${num}`
* return `Float: ${num.toFixed(2)}`
* }),
* Match.orElse(() => "Not a number type")
* )
*
* categorizeNumber(42) // => "Integer: 42"
* categorizeNumber(3.14) // => "Float: 3.14"
* categorizeNumber(NaN) // => "Not a number"
* categorizeNumber("hello") // => "Not a number type"
* ```
*
* @see {@link bigint} for matching primitive bigint values
*
* @stability stable
* @category guards
* @since 4.0.0
*/
export const number: Predicate.Refinement = Predicate.isNumber
/**
* Matches any value without restrictions.
*
* **When to use**
*
* Use to define an explicit catch-all pattern when the handler should receive
* the unmatched value.
*
* **Details**
*
* This predicate matches every input, including `undefined`, `null`, objects,
* primitives, and functions.
*
* **Gotchas**
*
* `Match.any` should usually be last because cases are checked in order and
* the first matching case wins.
*
* **Example** (Matching any remaining value)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* const describeValue = Match.type()
* .pipe(
* Match.when(Match.string, (str) => `String: ${str}`),
* Match.when(Match.number, (num) => `Number: ${num}`),
* Match.when(Match.boolean, (bool) => `Boolean: ${bool}`),
* Match.when(Match.any, (value) => `Other: ${typeof value}`),
* Match.exhaustive
* )
*
* describeValue("hello") // => "String: hello"
*
* describeValue(42) // => "Number: 42"
*
* describeValue([1, 2, 3]) // => "Other: object"
*
* describeValue(null) // => "Other: object"
* ```
*
* @see {@link defined} for matching only non-nullish values
* @see {@link orElse} for providing a fallback after earlier cases
*
* @stability stable
* @category guards
* @since 4.0.0
*/
export const any: SafeRefinement = internal.any
/**
* Matches any defined (non-null and non-undefined) value.
*
* **When to use**
*
* Use to exclude only `null` and `undefined` from a match branch.
*
* **Details**
*
* This predicate matches values that are neither `null` nor `undefined`,
* effectively filtering out nullish values while preserving all other types.
*
* **Example** (Matching defined values)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* const processValue = Match.type()
* .pipe(
* Match.when(Match.defined, (value) => `Defined value: ${value}`),
* Match.orElse(() => "Value is null or undefined")
* )
*
* processValue("hello") // => "Defined value: hello"
*
* processValue(42) // => "Defined value: 42"
*
* processValue(0) // => "Defined value: 0"
*
* processValue("") // => "Defined value: "
*
* processValue(null) // => "Value is null or undefined"
*
* processValue(undefined) // => "Value is null or undefined"
* ```
*
* @see {@link any} for matching every value without excluding nullish inputs
*
* @stability stable
* @category guards
* @since 4.0.0
*/
export const defined: (u: A) => u is A & {} = internal.defined
/**
* Matches values of type `boolean`.
*
* **When to use**
*
* Use to match primitive boolean values.
*
* **Details**
*
* This predicate refines unknown values to booleans, allowing pattern matching
* on boolean types. It only matches the primitive boolean values `true` and `false`.
*
* **Example** (Matching boolean values)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* const describeTruthiness = Match.type().pipe(
* Match.when(
* Match.boolean,
* (bool) => bool ? "Definitely true" : "Definitely false"
* ),
* Match.when(0, () => "Falsy number"),
* Match.when("", () => "Empty string"),
* Match.when(Match.null, () => "Null value"),
* Match.orElse(() => "Some other truthy value")
* )
*
* describeTruthiness(true) // => "Definitely true"
* describeTruthiness(false) // => "Definitely false"
* describeTruthiness(0) // => "Falsy number"
* describeTruthiness(1) // => "Some other truthy value"
* ```
*
* @see {@link is} for matching specific literal boolean values
*
* @stability stable
* @category guards
* @since 4.0.0
*/
export const boolean: Predicate.Refinement = Predicate.isBoolean
const _undefined: Predicate.Refinement = Predicate.isUndefined
export {
/**
* Matches the value `undefined`.
*
* **When to use**
*
* Use when a matcher should handle only inputs with no defined value.
*
* **Details**
*
* This refinement is backed by `Predicate.isUndefined`, which checks
* `input === undefined`.
*
* @see {@link defined} for matching non-nullish values
* @see {@link is} for matching literal values
*
* @stability stable
* @category guards
* @since 4.0.0
*/
_undefined as undefined
}
const _null: Predicate.Refinement = Predicate.isNull
export {
/**
* Matches the value `null`.
*
* **When to use**
*
* Use to handle only the `null` literal in a match branch.
*
* **Details**
*
* This refinement is backed by `Predicate.isNull`, which checks
* `input === null`.
*
* @see {@link defined} for matching non-nullish values
* @see {@link is} for matching literal values
*
* @stability stable
* @category guards
* @since 4.0.0
*/
_null as null
}
/**
* Matches values of type `bigint`.
*
* **When to use**
*
* Use to match primitive bigint values.
*
* **Details**
*
* This predicate refines unknown values to bigints, allowing pattern matching
* on bigint types. BigInts are used for representing integers with arbitrary precision.
*
* **Example** (Matching bigint values)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* const processLargeNumber = Match.type().pipe(
* Match.when(Match.bigint, (big) => {
* if (big > 9007199254740991n) {
* return `Large integer: ${big.toString()}`
* }
* return `BigInt: ${big.toString()}`
* }),
* Match.when(Match.number, (num) => `Regular number: ${num}`),
* Match.orElse(() => "Not a numeric type")
* )
*
* processLargeNumber(123n) // => "BigInt: 123"
* processLargeNumber(9007199254740992n) // => "Large integer: 9007199254740992"
* processLargeNumber(123) // => "Regular number: 123"
* processLargeNumber("123") // => "Not a numeric type"
* ```
*
* @see {@link number} for matching primitive number values
*
* @stability stable
* @category guards
* @since 4.0.0
*/
export const bigint: Predicate.Refinement = Predicate.isBigInt
/**
* Matches values of type `symbol`.
*
* **Details**
*
* This predicate refines unknown values to symbols, allowing pattern matching
* on symbol types. Symbols are unique identifiers that are often used as
* object keys or for creating private properties.
*
* **Example** (Matching symbol values)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* const mySymbol = Symbol("my-symbol")
* const globalSymbol = Symbol.for("global-symbol")
*
* const handleSymbol = Match.type().pipe(
* Match.when(Match.symbol, (sym) => {
* const description = sym.description
* if (description) {
* return `Symbol with description: ${description}`
* }
* return "Symbol without description"
* }),
* Match.orElse(() => "Not a symbol")
* )
*
* handleSymbol(mySymbol) // => "Symbol with description: my-symbol"
* handleSymbol(Symbol()) // => "Symbol without description"
* handleSymbol("string") // => "Not a symbol"
* ```
*
* @stability stable
* @category guards
* @since 4.0.0
*/
export const symbol: Predicate.Refinement = Predicate.isSymbol
/**
* Matches values that are instances of `Date`.
*
* **When to use**
*
* Use to match `Date` instances.
*
* **Details**
*
* This predicate refines unknown values to Date instances, allowing pattern
* matching on Date objects. It only matches actual Date instances, not
* date strings or timestamps.
*
* **Example** (Matching Date instances)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* const processDateValue = Match.type().pipe(
* Match.when(Match.date, (date) => {
* if (isNaN(date.getTime())) {
* return "Invalid date"
* }
* return `Date: ${date.toISOString().split("T")[0]}`
* }),
* Match.when(Match.string, (str) => `Date string: ${str}`),
* Match.orElse(() => "Not a date-related value")
* )
*
* processDateValue(new Date("2024-01-01")) // => "Date: 2024-01-01"
* processDateValue(new Date("invalid")) // => "Invalid date"
* processDateValue("2024-01-01") // => "Date string: 2024-01-01"
* processDateValue(1704067200000) // => "Not a date-related value"
* ```
*
* @see {@link instanceOf} for matching instances of any constructor
*
* @stability stable
* @category guards
* @since 4.0.0
*/
export const date: Predicate.Refinement = Predicate.isDate
/**
* Matches non-null objects other than arrays.
*
* **When to use**
*
* Use to match broad non-null, non-array object values.
*
* **Details**
*
* This predicate uses `Predicate.isObject`: it returns `true` for values whose
* runtime type is `"object"`, are not `null`, and are not arrays. It can match
* `Date`, `RegExp`, and class instances; use `instanceOf` or a more specific
* pattern when those cases need to be distinguished.
*
* **Example** (Matching record objects)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* const analyzeValue = Match.type().pipe(
* Match.when(Match.record, (obj) => {
* const keys = Object.keys(obj)
* const valueCount = keys.length
* return `Object with ${valueCount} properties: [${keys.join(", ")}]`
* }),
* Match.when(
* Match.instanceOf(Array),
* (arr) => `Array with ${arr.length} items`
* ),
* Match.orElse(() => "Not an object")
* )
*
* analyzeValue({ name: "Alice", age: 30 }) // => "Object with 2 properties: [name, age]"
* analyzeValue([1, 2, 3]) // => "Array with 3 items"
* analyzeValue(null) // => "Not an object"
* analyzeValue("hello") // => "Not an object"
* ```
*
* @see {@link instanceOf} for matching a specific constructor
*
* @stability stable
* @category guards
* @since 4.0.0
*/
export const record: Predicate.Refinement = Predicate.isObject
/**
* Matches instances of a given class.
*
* **When to use**
*
* Use to match values that are instances of a constructor with type-safe
* narrowing.
*
* **Details**
*
* This predicate checks if a value is an instance of the specified constructor,
* providing type-safe matching for class instances and built-in objects.
*
* **Example** (Matching class instances)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* class CustomError extends Error {
* constructor(message: string, public code: number) {
* super(message)
* }
* }
*
* const handleValue = Match.type()
* .pipe(
* Match.when(
* Match.instanceOf(CustomError),
* (err) => `Custom error: ${err.message} (code: ${err.code})`
* ),
* Match.when(
* Match.instanceOf(Error),
* (err) => `Standard error: ${err.message}`
* ),
* Match.when(
* Match.instanceOf(Array),
* (arr) => `Array with ${arr.length} items`
* ),
* Match.when(
* Match.instanceOf(Map),
* (map) => `Map with ${map.size} entries`
* ),
* Match.orElse((value) => `Other: ${typeof value}`)
* )
*
* handleValue(new CustomError("Failed", 404)) // => "Custom error: Failed (code: 404)"
* handleValue(new Error("Generic error")) // => "Standard error: Generic error"
* handleValue([1, 2, 3]) // => "Array with 3 items"
* handleValue(new Map([["count", 1]])) // => "Map with 1 entries"
* ```
*
* @see {@link instanceOfUnsafe} for constructor matching without the same type-safety guarantee
* @see {@link record} for matching broad non-null, non-array objects
*
* @stability stable
* @category guards
* @since 4.0.0
*/
export const instanceOf: any>(
constructor: A
) => SafeRefinement, never> = internal.instanceOf
/**
* Checks whether a value is an instance of a constructor without type-safe narrowing.
*
* **When to use**
*
* Use when you need constructor matching to use the unsafe refinement type.
*
* **Details**
*
* This predicate checks if a value is an instance of the specified constructor
* but doesn't provide the same type safety guarantees as the regular `instanceOf`.
* Use this when you need more flexibility but understand the type safety implications.
*
* **Example** (Matching class instances unsafely)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* class CustomError extends Error {
* constructor(message: string, public code: number) {
* super(message)
* }
* }
*
* // When you need to match instances but handle type narrowing manually
* const handleError = Match.type().pipe(
* Match.when(Match.instanceOfUnsafe(CustomError), (err: any) => {
* // Manual type assertion needed
* const customErr = err as CustomError
* return `Custom error ${customErr.code}: ${customErr.message}`
* }),
* Match.orElse(() => "Not a CustomError")
* )
* handleError(new CustomError("failed", 500)) // => "Custom error 500: failed"
* ```
*
* @see {@link instanceOf} for type-safe constructor matching
*
* @stability stable
* @category guards
* @since 4.0.0
*/
export const instanceOfUnsafe: any>(
constructor: A
) => SafeRefinement, InstanceType> = internal.instanceOf
/**
* Provides a fallback value when no patterns match.
*
* **When to use**
*
* Use to finalize a matcher with a fallback for unmatched input.
*
* **Details**
*
* This function ensures that a matcher always returns a valid result, even if
* no defined patterns match. It acts as a default case, similar to the
* `default` clause in a `switch` statement or the final `else` in an `if-else`
* chain.
*
* **Example** (Providing a default value when no patterns match)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* // Create a matcher for string or number values
* const match = Match.type().pipe(
* // Match when the value is "a"
* Match.when("a", () => "ok"),
* // Fallback when no patterns match
* Match.orElse(() => "fallback")
* )
*
* match("a") // => "ok"
*
* match("b") // => "fallback"
* ```
*
* @see {@link option} for finalizing unmatched input as `Option.none`
* @see {@link result} for returning unmatched input as a `Result` failure
* @see {@link orElseAbsurd} for finalizing when unmatched input should be impossible
*
* @stability stable
* @category completion
* @since 4.0.0
*/
export const orElse: , F extends (_: RA, ...args: Args) => Ret>(
f: F
) => (
self: Matcher
) => [Pr] extends [never] ? [Args] extends [[]] ? (input: I) => Unify | A>
: (...args: Args) => Unify | A>
: Unify | A> = internal.orElse
// TODO(4.0): Rename to "orThrow"? Like Result.getOrThrow
/**
* Returns a matcher that throws an error if no pattern matches.
*
* **When to use**
*
* Use to finalize a matcher when every remaining unmatched case should be
* impossible.
*
* **Details**
*
* This function finalizes a matcher by ensuring that if no patterns match, an
* error is thrown. It is useful when all cases should be covered, and any
* unexpected input should trigger an error instead of returning a default
* value.
*
* When used, this function removes the need for an explicit fallback case and
* ensures that an unmatched value is never silently ignored.
*
* **Example** (Throwing on unmatched input)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* const strictMatcher = Match.type<"a" | "b">().pipe(
* Match.when("a", () => "Found A"),
* Match.when("b", () => "Found B"),
* // Will throw if input is neither "a" nor "b"
* Match.orElseAbsurd
* )
*
* strictMatcher("a") // => "Found A"
* strictMatcher("b") // => "Found B"
*
* // This would throw an error at runtime:
* // strictMatcher("c" as any) // throws
* ```
*
* @see {@link exhaustive} for compile-time exhaustive matcher finalization
* @see {@link orElse} for providing a fallback for unmatched input
*
* @stability stable
* @category completion
* @since 4.0.0
*/
export const orElseAbsurd: >(
self: Matcher
) => [Pr] extends [never] ? [Args] extends [[]] ? (input: I) => Unify : (...args: Args) => Unify : Unify =
internal.orElseAbsurd
/**
* Wraps the match result in a `Result`, distinguishing matched and unmatched
* cases.
*
* **Details**
*
* This function ensures that the result of a matcher is always wrapped in an
* `Result`, allowing clear differentiation between successful matches
* (`Ok(value)`) and cases where no pattern matched (`Err(unmatched
* value)`).
*
* This approach is particularly useful when handling optional values or when an
* unmatched case should be explicitly handled rather than returning a default
* value or throwing an error.
*
* **Example** (Extracting a user role with `Match.result`)
*
* ```ts import.meta.vitest
* import { Match } from "effect"
*
* type User = { readonly role: "admin" | "editor" | "viewer" }
*
* // Create a matcher to extract user roles
* const getRole = Match.type().pipe(
* Match.when({ role: "admin" }, () => "Has full access"),
* Match.when({ role: "editor" }, () => "Can edit content"),
* Match.result // Wrap the result in an Result
* )
*
* getRole({ role: "admin" })._tag // => "Success"
*
* getRole({ role: "viewer" })._tag // => "Failure"
* ```
*
* @stability stable
* @category completion
* @since 4.0.0
*/
export const result: >(
self: Matcher