Socket
Socket
Sign inDemoInstall

ts-pattern

Package Overview
Dependencies
Maintainers
1
Versions
151
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-pattern - npm Package Compare versions

Comparing version 4.0.1-rc.16 to 4.0.1

4

dist/internals/helpers.d.ts

@@ -7,7 +7,7 @@ /**

import { SelectionType } from '../types/FindSelected';
import { Pattern, Matchable, MatcherType } from '../types/Pattern';
import { Pattern, Matcher, MatcherType } from '../types/Pattern';
export declare const isObject: (value: unknown) => value is Object;
export declare const isMatchable: (x: unknown) => x is Matchable<unknown, unknown, MatcherType, SelectionType, unknown>;
export declare const isMatcher: (x: unknown) => x is Matcher<unknown, unknown, MatcherType, SelectionType, unknown>;
export declare const matchPattern: (pattern: Pattern<any>, value: any, select: (key: string, value: unknown) => void) => boolean;
export declare const getSelectionKeys: (pattern: Pattern<any>) => string[];
export declare const flatMap: <T, U>(xs: T[], f: (v: T) => U[]) => U[];

@@ -5,17 +5,30 @@ import { Pattern } from './types/Pattern';

/**
* Helper function taking a pattern and returning a **type guard** function telling
* us whether or not a value matches the pattern.
* `isMatching` takes pattern and returns a **type guard** function, cheching if a value matches this pattern.
*
* @param pattern the Pattern the value should match
* @returns a function taking the value and returning whether or not it matches the pattern.
* [Read `isMatching` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#ismatching)
*
* @example
* const hasName = isMatching({ name: P.string })
*
* declare let input: unknown
*
* if (hasName(input)) {
* // `input` inferred as { name: string }
* return input.name
* }
*/
export declare function isMatching<p extends Pattern<any>>(pattern: p): (value: any) => value is MatchedValue<any, P.infer<p>>;
/**
* **type guard** function taking a pattern and a value and returning a boolean telling
* us whether or not the value matches the pattern.
* `isMatching` takes pattern and a value and checks if the value matches this pattern.
*
* @param pattern the Pattern the value should match
* @param value
* @returns a boolean telling whether or not the value matches the pattern.
* [Read `isMatching` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#ismatching)
*
* @example
* declare let input: unknown
*
* if (isMatching({ name: P.string }, input)) {
* // `input` inferred as { name: string }
* return input.name
* }
*/
export declare function isMatching<p extends Pattern<any>>(pattern: p, value: any): value is MatchedValue<any, P.infer<p>>;
import { Match } from './types/Match';
import * as symbols from './internals/symbols';
/**
* #### match
* `match` creates a **pattern matching expression**.
*
* Entry point to create a pattern matching expression.
* [Read `match` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#match)
*
* It returns a `Match` builder, on which you can chain
* several `.with(pattern, handler)` clauses.
* Use `.with(pattern, handler)` to pattern match on the input.
*
* Use `.exhaustive()` or `.otherwise(() => defaultValue)` to end the expression and get the result.
*
* @example
* declare let input: "A" | "B";
*
* return match(input)
* .with("A", () => "It's a A!")
* .with("B", () => "It's a B!")
* .exhaustive();
*
*/
export declare const match: <input, output = typeof symbols.unset>(value: input) => Match<input, output, [], never>;

@@ -7,5 +7,7 @@ import * as symbols from './internals/symbols';

/**
* ### infer
* `P.infer<typeof somePattern>` will return the type of the value
* matched by this pattern
* matched by this pattern.
*
* [Read `P.infer` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#Pinfer)
*
* @example

@@ -17,6 +19,8 @@ * const userPattern = { name: P.stringΒ }

/**
* ### Optional pattern
* `P.optional(subpattern)` takes a sub pattern and returns a pattern which matches if the
* key is undefined or if it is defined and the sub pattern matches its value.
* @example
*
* [Read `P.optional` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#Poptional-patterns)
* @example
* match(value)

@@ -28,5 +32,7 @@ * .with({ greeting: P.optional('Hello') }, () => 'will match { greeting?: "Hello"Β }')

/**
* ### Array pattern
* `P.array(subpattern)` takes a sub pattern and returns a pattern, which matches
* arrays if all their elements match the sub pattern.
*
* [Read `P.array` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#Parray-patterns)
*
* @example

@@ -38,5 +44,7 @@ * match(value)

/**
* ### Intersection pattern
* `P.intersection(...patterns)` returns a pattern which matches
* only if **every** patterns provided in parameter match the input.
*
* [Read `P.intersection` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#Pintersection-patterns)
*
* @example

@@ -57,5 +65,7 @@ * match(value)

/**
* ### Union pattern
* `P.union(...patterns)` returns a pattern which matches
* if **at least one** of the patterns provided in parameter match the input.
*
* [Read `P.union` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#Punion-patterns)
*
* @example

@@ -72,5 +82,7 @@ * match(value)

/**
* ### Not pattern
* `P.not(pattern)` returns a pattern which matches if the sub pattern
* doesn't match.
*
* [Read `P.not` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#Pnot-patterns)
*
* @example

@@ -83,5 +95,7 @@ * match<{ a: string | number }>(value)

/**
* ### When pattern
* `P.when((value) => boolean)` returns a pattern which matches
* if the predicate returns true for the current input.
*
* [Read `P.when` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#Pwhen-patterns)
*
* @example

@@ -95,5 +109,7 @@ * match<{ age: number }>(value)

/**
* ### Select pattern
* `P.select()` is a pattern which will always match,
* and will inject the selected piece of input in the handler function.
*
* [Read `P.select` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#Pselect-patterns)
*
* @example

@@ -109,4 +125,6 @@ * match<{ age: number }>(value)

/**
* ### Catch All wildcard
* `P.any` is a wildcard pattern, matching **any value**.
*
* [Read `P.any` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#P_-wildcard)
*
* @example

@@ -118,5 +136,7 @@ * match(value)

/**
* ### Catch All wildcard
* `P._` is a wildcard pattern, matching **any value**.
* It's an alias to `P.any`.
*
* [Read `P._` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#P_-wildcard)
*
* @example

@@ -128,4 +148,6 @@ * match(value)

/**
* ### String wildcard
* `P.string` is a wildcard pattern matching any **string**.
*
* [Read `P.string` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#Pstring-wildcard)
*
* @example

@@ -137,4 +159,6 @@ * match(value)

/**
* ### Number wildcard
* `P.number` is a wildcard pattern matching any **number**.
*
* [Read `P.number` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#Pnumber-wildcard)
*
* @example

@@ -146,4 +170,6 @@ * match(value)

/**
* ### Boolean wildcard
* `P.boolean` is a wildcard pattern matching any **boolean**.
*
* [Read `P.boolean` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#boolean-wildcard)
*
* @example

@@ -154,4 +180,6 @@ * .with(P.boolean, () => 'will match on booleans')

/**
* ### BigInt wildcard
* `P.bigint` is a wildcard pattern matching any **bigint**.
*
* [Read `P.bigint` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#bigint-wildcard)
*
* @example

@@ -162,4 +190,6 @@ * .with(P.bigint, () => 'will match on bigints')

/**
* ### Symbol wildcard
* `P.symbol` is a wildcard pattern matching any **symbol**.
*
* [Read `P.symbol` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#symbol-wildcard)
*
* @example

@@ -170,4 +200,6 @@ * .with(P.symbol, () => 'will match on symbols')

/**
* ### Nullish wildcard
* `P.nullish` is a wildcard pattern matching **null** or **undefined**.
*
* [Read `P.nullish` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#nullish-wildcard)
*
* @example

@@ -178,5 +210,7 @@ * .with(P.nullish, () => 'will match on null or undefined')

/**
* ### instanceOf
* `P.instanceOf(SomeClass)` is a pattern matching instances of a given class.
* @example
*
* [Read `P.instanceOf` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#Pinstanceof-patterns)
*
* @example
* .with(P.instanceOf(SomeClass), () => 'will match on SomeClass instances')

@@ -186,8 +220,15 @@ */

/**
* ### typed
* `P.typed<SomeType>()` is a way to set the input type this
* pattern should match.
* pattern should match on.
*
* It returns all utility functions to create patterns,
* Like `array`, `union`, `intersection`, etc.
*
* [Read `P.typed` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#Ptyped)
*
* @example
* .with(
* P.typed<string | number[]>().array(P.string),
* (arrayOfString) => arrayOfString.join(', ')
* )
*/

@@ -194,0 +235,0 @@ export declare function typed<input>(): {

import type * as symbols from '../internals/symbols';
import type { Cast, Equal, IsAny, TupleKeys, UnionToTuple } from './helpers';
import type { Matchable, Pattern } from './Pattern';
import type { Matcher, Pattern } from './Pattern';
declare type SelectionsRecord = Record<string, [unknown, unknown[]]>;

@@ -20,3 +20,3 @@ export declare type None = {

declare type ReduceFindSelectionUnion<i, ps extends any[], output = never> = ps extends [infer head, ...infer tail] ? ReduceFindSelectionUnion<i, tail, output | FindSelectionUnion<i, head>> : output;
export declare type FindSelectionUnion<i, p, path extends any[] = []> = IsAny<i> extends true ? never : p extends Matchable<any, infer pattern, infer matcherType, infer sel> ? {
export declare type FindSelectionUnion<i, p, path extends any[] = []> = IsAny<i> extends true ? never : p extends Matcher<any, infer pattern, infer matcherType, infer sel> ? {
select: sel extends Some<infer k> ? {

@@ -23,0 +23,0 @@ [kk in k]: [i, path];

import { DeepExclude } from './DeepExclude';
import { IsPlainObject, Primitives, IsLiteral, ValueOf, Compute, Cast, Equal } from './helpers';
import type { Matchable, ToExclude } from './Pattern';
import type { Matcher, ToExclude } from './Pattern';
declare type OptionalKeys<p> = ValueOf<{
[k in keyof p]: p[k] extends Matchable<any, any, infer matcherType> ? matcherType extends 'optional' ? k : never : never;
[k in keyof p]: p[k] extends Matcher<any, any, infer matcherType> ? matcherType extends 'optional' ? k : never : never;
}>;

@@ -17,3 +17,3 @@ declare type ReduceUnion<tuple extends any[], output = never> = tuple extends readonly [

*/
export declare type InvertPattern<p> = p extends Matchable<infer input, infer narrowed, infer matcherType, any> ? {
export declare type InvertPattern<p> = p extends Matcher<infer input, infer narrowed, infer matcherType, any> ? {
not: ToExclude<InvertPattern<narrowed>>;

@@ -50,3 +50,3 @@ select: InvertPattern<narrowed>;

*/
export declare type InvertPatternForExclude<p, i, empty = never> = p extends Matchable<infer matchableInput, infer subpattern, infer matcherType, any, infer excluded> ? {
export declare type InvertPatternForExclude<p, i, empty = never> = p extends Matcher<infer matchableInput, infer subpattern, infer matcherType, any, infer excluded> ? {
select: InvertPatternForExclude<subpattern, i, empty>;

@@ -53,0 +53,0 @@ array: i extends readonly (infer ii)[] ? InvertPatternForExclude<subpattern, ii, empty>[] : empty;

import type * as symbols from '../internals/symbols';
import type { Pattern, Matchable } from './Pattern';
import type { Pattern, Matcher } from './Pattern';
import type { ExtractPreciseValue } from './ExtractPreciseValue';

@@ -19,6 +19,6 @@ import type { InvertPatternForExclude, InvertPattern } from './InvertPattern';

/**
* #### Match.with
* `.with(pattern, handler)` Registers a pattern and an handler function which
* will be called if this pattern matches the input value.
*
* If the input matches the pattern provided as first argument,
* execute the handler function and return its result.
* [Read `.with()` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#with)
**/

@@ -53,24 +53,23 @@ with<p extends Pattern<i>, c, value extends MatchedValue<i, InvertPattern<p>>>(pattern: p, handler: (selections: FindSelected<value, p>, value: value) => PickReturnValue<o, c>): Match<i, o, [...patternValueTuples, [p, value]], Union<inferredOutput, c>>;

], Union<inferredOutput, c>>;
with<pat extends Pattern<i>, pred extends (value: MatchedValue<i, InvertPattern<pat>>) => unknown, c, value extends GuardValue<pred>>(pattern: pat, predicate: pred, handler: (selections: FindSelected<value, pat>, value: value) => PickReturnValue<o, c>): Match<i, o, pred extends (value: any) => value is infer narrowed ? [...patternValueTuples, [Matchable<unknown, narrowed>, value]] : patternValueTuples, Union<inferredOutput, c>>;
with<pat extends Pattern<i>, pred extends (value: MatchedValue<i, InvertPattern<pat>>) => unknown, c, value extends GuardValue<pred>>(pattern: pat, predicate: pred, handler: (selections: FindSelected<value, pat>, value: value) => PickReturnValue<o, c>): Match<i, o, pred extends (value: any) => value is infer narrowed ? [...patternValueTuples, [Matcher<unknown, narrowed>, value]] : patternValueTuples, Union<inferredOutput, c>>;
/**
* #### Match.when
* `.when(predicate, handler)` Registers a predicate function and an handler function.
* If the predicate returns true, the handler function will be chosen to handle the input.
*
* When the first function returns a truthy value,
* execute the handler function and return its result.
* [Read `.when()` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#when)
**/
when<pred extends (value: i) => unknown, c, value extends GuardValue<pred>>(predicate: pred, handler: (value: value) => PickReturnValue<o, c>): Match<i, o, pred extends (value: any) => value is infer narrowed ? [...patternValueTuples, [Matchable<unknown, narrowed>, value]] : patternValueTuples, Union<inferredOutput, c>>;
when<pred extends (value: i) => unknown, c, value extends GuardValue<pred>>(predicate: pred, handler: (value: value) => PickReturnValue<o, c>): Match<i, o, pred extends (value: any) => value is infer narrowed ? [...patternValueTuples, [Matcher<unknown, narrowed>, value]] : patternValueTuples, Union<inferredOutput, c>>;
/**
* #### Match.otherwise
* `.otherwise()` takes a function returning the **default value**, and
* will be used to handle the input value if no previous pattern matched.
*
* takes a function returning the **default value**.
* and return the result of the pattern matching expression.
* Equivalent to `.with(P._, () => x).exhaustive()`
*
* Equivalent to `.with(P._, () => x).exhaustive()`
* [Read `.otherwise()` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#otherwise)
*
**/
otherwise<c>(handler: (value: i) => PickReturnValue<o, c>): PickReturnValue<o, Union<inferredOutput, c>>;
/**
* #### Match.exhaustive
* `.exhaustive()` runs the pattern matching expression and return the result value.
*
* Runs the pattern matching expression and return the result value.
*
* If this is of type `NonExhaustiveError`, it means you aren't matching

@@ -80,7 +79,8 @@ * every case, and you should add another `.with(...)` clause

*
* [Read `.exhaustive()` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#exhaustive)
*
* */
exhaustive: DeepExcludeAll<i, patternValueTuples> extends infer remainingCases ? [remainingCases] extends [never] ? () => PickReturnValue<o, inferredOutput> : NonExhaustiveError<remainingCases> : never;
/**
* #### Match.run
* Runs the pattern matching expression and return the result.
* `.run()` runs the pattern matching expression and return the result value.
* */

@@ -87,0 +87,0 @@ run(): PickReturnValue<o, inferredOutput>;

@@ -14,14 +14,21 @@ import type * as symbols from '../internals/symbols';

};
export interface Matchable<input, narrowed, matcherType extends MatcherType = 'default', selections extends SelectionType = None, excluded = narrowed> {
/**
* A `Matcher` is an object implementing the match
* protocol. It must define a `symbols.matcher` property
* which returns an object with a `match()` method, taking
* the input value and returning whether the pattern matches
* or not, along with optional selections.
*/
export interface Matcher<input, narrowed, matcherType extends MatcherType = 'default', selections extends SelectionType = None, excluded = narrowed> {
[symbols.matcher](): MatcherProtocol<input, narrowed, matcherType, selections, excluded>;
}
declare type AnyMatchable = Matchable<unknown, unknown, any, any>;
export declare type OptionalP<input, p> = Matchable<input, p, 'optional'>;
export declare type ArrayP<input, p> = Matchable<input, p, 'array'>;
export declare type AndP<input, ps> = Matchable<input, ps, 'and'>;
export declare type OrP<input, ps> = Matchable<input, ps, 'or'>;
export declare type NotP<input, p> = Matchable<input, p, 'not'>;
export declare type GuardP<input, narrowed> = Matchable<input, narrowed>;
export declare type GuardExcludeP<input, narrowed, excluded> = Matchable<input, narrowed, 'default', None, excluded>;
export declare type SelectP<key extends string, input = unknown, p = Matchable<unknown, unknown>> = Matchable<input, p, 'select', Some<key>>;
declare type UnknownMatcher = Matcher<unknown, unknown, any, any>;
export declare type OptionalP<input, p> = Matcher<input, p, 'optional'>;
export declare type ArrayP<input, p> = Matcher<input, p, 'array'>;
export declare type AndP<input, ps> = Matcher<input, ps, 'and'>;
export declare type OrP<input, ps> = Matcher<input, ps, 'or'>;
export declare type NotP<input, p> = Matcher<input, p, 'not'>;
export declare type GuardP<input, narrowed> = Matcher<input, narrowed>;
export declare type GuardExcludeP<input, narrowed, excluded> = Matcher<input, narrowed, 'default', None, excluded>;
export declare type SelectP<key extends string, input = unknown, p = Matcher<unknown, unknown>> = Matcher<input, p, 'select', Some<key>>;
export declare type AnonymousSelectP = SelectP<symbols.anonymousSelectKey>;

@@ -33,9 +40,15 @@ export interface ToExclude<a> {

readonly [k: string]: UnknownPattern;
} | Set<UnknownPattern> | Map<unknown, UnknownPattern> | Primitives | AnyMatchable;
} | Set<UnknownPattern> | Map<unknown, UnknownPattern> | Primitives | UnknownMatcher;
/**
* ### Pattern
* Patterns can be any (nested) javascript value.
* They can also be a "wildcards", like `_`.
* `Pattern<a>` is the generic type for patterns matching a value of type `a`. A pattern can be any (nested) javascript value.
*
* They can also be wildcards, like `P._`, `P.string`, `P.number`,
* or other matchers, like `P.when(predicate)`, `P.not(pattern)`, etc.
*
* [Read `Patterns` documentation on GitHub](https://github.com/gvergnaud/ts-pattern#patterns)
*
* @example
* const pattern: P.Pattern<User> = { name: P.stringΒ }
*/
export declare type Pattern<a> = Matchable<a, unknown, any, any> | (a extends Primitives ? a : unknown extends a ? UnknownPattern : a extends readonly (infer i)[] ? a extends readonly [infer a1, infer a2, infer a3, infer a4, infer a5] ? readonly [
export declare type Pattern<a> = Matcher<a, unknown, any, any> | (a extends Primitives ? a : unknown extends a ? UnknownPattern : a extends readonly (infer i)[] ? a extends readonly [infer a1, infer a2, infer a3, infer a4, infer a5] ? readonly [
Pattern<a1>,

@@ -42,0 +55,0 @@ Pattern<a2>,

{
"name": "ts-pattern",
"version": "4.0.1-rc.16",
"version": "4.0.1",
"description": " The exhaustive Pattern Matching library for TypeScript.",

@@ -5,0 +5,0 @@ "type": "module",

@@ -46,3 +46,3 @@ <h1 align="center">ts-pattern</h1>

- Works on **any data structure**: nested objects, arrays, tuples, Sets, Maps and all primitive types.
- Works on **any data structure**: nested [Objects](#objects), [Arrays](#tuples-arrays), [Tuples](#tuples-arrays), [Sets](#sets), [Maps](#maps) and all primitive types.
- **Typesafe**, with helpful type inference.

@@ -49,0 +49,0 @@ - **Exhaustiveness checking** support, enforcing that you are matching every possible case with [`.exhaustive()`](#exhaustive).

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚑️ by Socket Inc