or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-ts-pattern

The exhaustive Pattern Matching library for TypeScript with smart type inference

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/ts-pattern@5.8.x

To install, run

npx @tessl/cli install tessl/npm-ts-pattern@5.8.0

0

# TS-Pattern

1

2

TS-Pattern is the exhaustive Pattern Matching library for TypeScript with smart type inference. It brings the power of pattern matching from functional programming languages to TypeScript, enabling you to write safer, more expressive conditional logic with compile-time exhaustiveness checking.

3

4

## Package Information

5

6

- **Package Name**: ts-pattern

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install ts-pattern`

10

11

## Core Imports

12

13

```typescript

14

import { match, P, isMatching, NonExhaustiveError } from "ts-pattern";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const { match, P, isMatching, NonExhaustiveError } = require("ts-pattern");

21

```

22

23

## Basic Usage

24

25

```typescript

26

import { match, P } from "ts-pattern";

27

28

type Data =

29

| { type: 'text'; content: string }

30

| { type: 'img'; src: string };

31

32

type Result =

33

| { type: 'ok'; data: Data }

34

| { type: 'error'; error: Error };

35

36

const result: Result = { type: 'ok', data: { type: 'text', content: 'Hello' } };

37

38

const html = match(result)

39

.with({ type: 'error' }, () => 'Error occurred')

40

.with({ type: 'ok', data: { type: 'text' } }, (res) => res.data.content)

41

.with({ type: 'ok', data: { type: 'img', src: P.select() } }, (src) => `<img src="${src}" />`)

42

.exhaustive();

43

```

44

45

## Architecture

46

47

TS-Pattern is built around several key components:

48

49

- **Match Expression API**: The core `match(value)` function creating chainable pattern matching expressions

50

- **Pattern Library (P)**: Comprehensive pattern matching utilities including wildcards, predicates, and combinators

51

- **Type Safety**: Full TypeScript integration with smart type inference and exhaustiveness checking

52

- **Validation API**: `isMatching` function for type guards and runtime validation

53

- **Builder Pattern**: Fluent chainable API for constructing complex pattern matching logic

54

55

## Capabilities

56

57

### Pattern Matching

58

59

Core pattern matching functionality for creating exhaustive conditional logic with type safety. Ideal for handling union types, API responses, and complex state machines.

60

61

```typescript { .api }

62

/**

63

* Creates a pattern matching expression

64

* @param value - Input value to match against patterns

65

* @returns Match expression for chaining patterns

66

*/

67

function match<const input, output = unknown>(

68

value: input

69

): Match<input, output>;

70

71

interface Match<input, output> {

72

/** Match against a pattern with handler function */

73

with<const pattern extends Pattern<input>>(

74

pattern: pattern,

75

handler: (selections: P.infer<pattern>, value: input) => output

76

): Match<input, output>;

77

78

/** Match against a pattern with guard and handler */

79

with<const pattern extends Pattern<input>>(

80

pattern: pattern,

81

guard: (value: input) => unknown,

82

handler: (selections: P.infer<pattern>, value: input) => output

83

): Match<input, output>;

84

85

/** Match against multiple patterns with single handler */

86

with<const patterns extends readonly Pattern<input>[]>(

87

...args: [...patterns, (selections: any, value: input) => output]

88

): Match<input, output>;

89

90

/** Match based on predicate function */

91

when(

92

predicate: (value: input) => unknown,

93

handler: (value: input) => output

94

): Match<input, output>;

95

96

/** Provide default case and return result */

97

otherwise(handler: (value: input) => output): output;

98

99

/** Ensure exhaustive matching and return result */

100

exhaustive(unexpectedValueHandler?: (value: input) => never): output;

101

}

102

```

103

104

[Pattern Matching](./pattern-matching.md)

105

106

### Pattern Library

107

108

Comprehensive pattern construction utilities including wildcards, type-specific patterns, and combinators for building complex matching logic.

109

110

```typescript { .api }

111

// Wildcard patterns

112

const any: AnyPattern;

113

const _: AnyPattern; // alias for any

114

const string: StringPattern;

115

const number: NumberPattern;

116

const bigint: BigIntPattern;

117

const boolean: BooleanPattern;

118

const symbol: SymbolPattern;

119

const nullish: NullishPattern;

120

const nonNullable: NonNullablePattern;

121

122

// Pattern constructor functions

123

function optional<input, const pattern extends Pattern<input>>(

124

pattern: pattern

125

): Chainable<OptionalP<input, pattern>>;

126

127

function array<input, const pattern extends Pattern<UnwrapArray<input>>>(

128

pattern?: pattern

129

): ArrayChainable<ArrayP<input, pattern>>;

130

131

function union<input, const patterns extends readonly Pattern<input>[]>(

132

...patterns: patterns

133

): Chainable<OrP<input, patterns>>;

134

135

function intersection<input, const patterns extends readonly Pattern<input>[]>(

136

...patterns: patterns

137

): Chainable<AndP<input, patterns>>;

138

```

139

140

[Pattern Library](./patterns.md)

141

142

### Type Validation

143

144

Runtime type validation and type guard generation using pattern matching. Perfect for validating API responses, user input, and unknown data structures.

145

146

```typescript { .api }

147

/**

148

* Creates a type guard function from a pattern

149

* @param pattern - Pattern to match against

150

* @returns Type guard function

151

*/

152

function isMatching<const p extends Pattern<unknown>>(

153

pattern: p

154

): (value: unknown) => value is P.infer<p>;

155

156

/**

157

* Validates if a value matches a pattern

158

* @param pattern - Pattern to match against

159

* @param value - Value to validate

160

* @returns Boolean indicating if value matches pattern

161

*/

162

function isMatching<const T, const P extends Pattern<T>>(

163

pattern: P,

164

value: T

165

): value is T & P.infer<P>;

166

```

167

168

[Type Validation](./validation.md)

169

170

## Error Handling

171

172

```typescript { .api }

173

/**

174

* Error thrown when no pattern matches in exhaustive matching

175

*/

176

class NonExhaustiveError extends Error {

177

constructor(input: unknown);

178

input: unknown;

179

}

180

```

181

182

## Type Definitions

183

184

```typescript { .api }

185

// Core pattern type

186

type Pattern<T> =

187

| T

188

| Matcher<any, any, any, any, any>

189

| (T extends readonly (infer U)[] ? Pattern<U>[] : never)

190

| (T extends object ? { [K in keyof T]?: Pattern<T[K]> } : never);

191

192

// Pattern inference

193

type infer<pattern> = InvertPattern<NoInfer<pattern>, unknown>;

194

195

// Pattern narrowing

196

type narrow<input, pattern> = ExtractPreciseValue<

197

input,

198

InvertPattern<pattern, input>

199

>;

200

```