Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add P.nonNullable patterns #229

Merged
merged 4 commits into from
Mar 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -792,14 +792,14 @@ type Input =
| [number, '*', number]
| ['-', number];

const input: Input = [3, '*', 4];
const input = [3, '*', 4] as Input;

const output = match(input)
.with([P._, '+', P._], ([x, , y]) => x + y)
.with([P._, '-', P._], ([x, , y]) => x - y)
.with([P._, '*', P._], ([x, , y]) => x * y)
.with(['-', P._], ([, x]) => -x)
.otherwise(() => NaN);
.exhaustive();

console.log(output);
// => 12
Expand Down Expand Up @@ -896,14 +896,29 @@ const input = null;
const output = match<number | null | undefined>(input)
.with(P.number, () => 'it is a number!')
.with(P.nullish, () => 'it is either null or undefined!')
.with(null, () => 'it is null!')
.with(undefined, () => 'it is undefined!')
.exhaustive();

console.log(output);
// => 'it is either null or undefined!'
```

#### `P.nonNullable` wildcard

The `P.nonNullable` pattern will match any value except `null` or `undefined`.

```ts
import { match, P } from 'ts-pattern';

const input = null;

const output = match<number | null | undefined>(input)
.with(P.nonNullable, () => 'it is a number!')
.otherwise(() => 'it is either null or undefined!');

console.log(output);
// => 'it is either null or undefined!'
```

#### `P.bigint` wildcard

The `P.bigint` pattern will match any value of type `bigint`.
Expand Down
3 changes: 3 additions & 0 deletions docs/roadmap.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
### Roadmap

- [ ] `P.array.includes(x)`
- [ ] `P.record({Pkey}, {Pvalue})`
- [x] `P.nonNullable`
- [x] chainable methods
- [x] string
- [x] `P.string.includes('str')`
Expand Down
23 changes: 19 additions & 4 deletions src/patterns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
StringChainable,
ArrayChainable,
Variadic,
NonNullablePattern,
} from './types/Pattern';

export type { Pattern, Fn as unstable_Fn };
Expand Down Expand Up @@ -634,6 +635,10 @@ function isNullish<T>(x: T | null | undefined): x is null | undefined {
return x === null || x === undefined;
}

function isNonNullable(x: unknown): x is {} {
return x !== null && x !== undefined;
}

type AnyConstructor = abstract new (...args: any[]) => any;

function isInstanceOf<T extends AnyConstructor>(classConstructor: T) {
Expand Down Expand Up @@ -928,7 +933,7 @@ export const number: NumberPattern = numberChainable(when(isNumber));
*
* @example
* match(value)
* .with(P.bigint.between(0, 10), () => '0 <= numbers <= 10')
* .with(P.bigint.between(0, 10), () => '0 <= bigints <= 10')
*/
const betweenBigInt = <
input,
Expand All @@ -947,7 +952,7 @@ const betweenBigInt = <
*
* @example
* match(value)
* .with(P.bigint.lt(10), () => 'numbers < 10')
* .with(P.bigint.lt(10), () => 'bigints < 10')
*/
const ltBigInt = <input, const max extends bigint>(
max: max
Expand All @@ -961,7 +966,7 @@ const ltBigInt = <input, const max extends bigint>(
*
* @example
* match(value)
* .with(P.bigint.gt(10), () => 'numbers > 10')
* .with(P.bigint.gt(10), () => 'bigints > 10')
*/
const gtBigInt = <input, const min extends bigint>(
min: min
Expand Down Expand Up @@ -1072,10 +1077,20 @@ export const symbol: SymbolPattern = chainable(when(isSymbol));
* [Read the documentation for `P.nullish` on GitHub](https://github.com/gvergnaud/ts-pattern#nullish-wildcard)
*
* @example
* .with(P.nullish, () => 'will match on null or undefined')
* .with(P.nullish, (x) => `${x} is null or undefined`)
*/
export const nullish: NullishPattern = chainable(when(isNullish));

/**
* `P.nonNullable` is a wildcard pattern, matching everything except **null** or **undefined**.
*
* [Read the documentation for `P.nonNullable` on GitHub](https://github.com/gvergnaud/ts-pattern#nonNullable-wildcard)
*
* @example
* .with(P.nonNullable, (x) => `${x} isn't null nor undefined`)
*/
export const nonNullable: NonNullablePattern = chainable(when(isNonNullable));

/**
* `P.instanceOf(SomeClass)` is a pattern matching instances of a given class.
*
Expand Down
11 changes: 4 additions & 7 deletions src/types/Pattern.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
import type * as symbols from '../internals/symbols';
import {
LeastUpperBound,
MergeUnion,
Primitives,
WithDefault,
} from './helpers';
import { MergeUnion, Primitives, WithDefault } from './helpers';
import { None, Some, SelectionType } from './FindSelected';
import { matcher, narrow } from '../patterns';
import { matcher } from '../patterns';
import { ExtractPreciseValue } from './ExtractPreciseValue';

export type MatcherType =
Expand Down Expand Up @@ -192,6 +187,8 @@ export type NullishPattern = Chainable<
never
>;

export type NonNullablePattern = Chainable<GuardP<unknown, {}>, never>;

type MergeGuards<input, guard1, guard2> = [guard1, guard2] extends [
GuardExcludeP<any, infer narrowed1, infer excluded1>,
GuardExcludeP<any, infer narrowed2, infer excluded2>
Expand Down
21 changes: 21 additions & 0 deletions tests/wildcards.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,27 @@ describe('wildcards', () => {
expect(res2).toEqual(true);
});

it('should match nonNullable wildcard', () => {
type Input = string | number | boolean | null | undefined;
const res = match<Input>(false)
.with(P.nonNullable, (x) => {
type t = Expect<Equal<typeof x, string | number | boolean>>;
return true;
})
.otherwise(() => false);

const res2 = match<0 | 1 | 2 | null>(0)
.with(P.nonNullable, (x) => {
type t = Expect<Equal<typeof x, 0 | 1 | 2>>;
return true;
})
.with(null, () => false)
.exhaustive();

expect(res).toEqual(true);
expect(res2).toEqual(true);
});

it('should match String, Number and Boolean wildcards', () => {
// Will be { id: number, title: string } | { errorMessage: string }
let httpResult = {
Expand Down