Skip to content

Commit eb14da5

Browse files
committed
feat(narrow): Add docs
1 parent 1856ad3 commit eb14da5

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

README.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ Type-Level TypeScript takes you on a deep dive into the most advanced features o
101101
- [`.returnType`](#returntype)
102102
- [`.exhaustive`](#exhaustive)
103103
- [`.otherwise`](#otherwise)
104+
- [`.narrow`](#narrow)
104105
- [`isMatching`](#ismatching)
105106
- [Patterns](#patterns)
106107
- [Literals](#literals)
@@ -640,6 +641,43 @@ returns the result of the pattern-matching expression, or **throws** if no patte
640641
function run(): TOutput;
641642
```
642643

644+
### `.narrow`
645+
646+
```ts
647+
match(...)
648+
.with(...)
649+
.narrow()
650+
.with(...)
651+
```
652+
653+
The `.narrow()` method deeply narrows the input type to exclude all values that have previously been handled. This is useful when you want to exclude cases from union types or nullable properties that are deeply nested.
654+
655+
Note that handled case of top-level union types are excluded by default, without calling `.narrow()`.
656+
657+
#### Signature
658+
659+
```ts
660+
function narrow(): Match<Narrowed<TInput>, TOutput>;
661+
```
662+
663+
#### Example
664+
665+
```ts
666+
type Input = { color: 'red' | 'blue'; size: 'small' | 'large' };
667+
668+
declare const input: Input;
669+
670+
const result = match(input)
671+
.with({ color: 'red', size: 'small' }, (red) => `Red: ${red.size}`)
672+
.with({ color: 'blue', size: 'large' }, (red) => `Red: ${red.size}`)
673+
.narrow() // 👈
674+
.otherwise((narrowedInput) => {
675+
// narrowedInput:
676+
// | { color: 'red'; size: 'large' }
677+
// | { color: 'blue'; size: 'small' }
678+
});
679+
```
680+
643681
### `isMatching`
644682

645683
```ts

0 commit comments

Comments
 (0)