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

Add P.object and P.object.empty #233

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 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
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ TS-Pattern assumes that [Strict Mode](https://www.typescriptlang.org/tsconfig#st
- [`P.intersection` patterns](#pintersection-patterns)
- [`P.string` predicates](#pstring-predicates)
- [`P.number` and `P.bigint` predicates](#pnumber-and-pbigint-predicates)
- [`P.object` predicates](#pobject-predicates)
- [Types](#types)
- [`P.infer`](#pinfer)
- [`P.Pattern`](#pPattern)
Expand Down Expand Up @@ -1482,6 +1483,23 @@ const fn = (input: number) =>
console.log(fn(-3.141592), fn(7)); // logs '✅ ❌'
```

## `P.object` predicates

`P.object` has a number of methods to help you match on specific object.

### `P.object.empty`

`P.object.empty` matches empty object

```ts
const fn = (input: string) =>
match(input)
.with(P.object.empty(), () => 'Empty!')
.otherwise(() => 'Full!');

console.log(fn({})); // Empty!
```

## Types

### `P.infer`
Expand Down
39 changes: 39 additions & 0 deletions src/patterns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
StringChainable,
ArrayChainable,
Variadic,
ObjectChainable,
} from './types/Pattern';

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

function isObject<T>(x: T | object): x is object {
return typeof x === 'object' &&
!Array.isArray(x) &&
x !== null
}

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

function isInstanceOf<T extends AnyConstructor>(classConstructor: T) {
Expand Down Expand Up @@ -1110,3 +1117,35 @@ export function shape<input, const pattern extends Pattern<input>>(
export function shape(pattern: UnknownPattern) {
return chainable(when(isMatching(pattern)));
}

/**
* `P.object.empty()` is a pattern, matching **objects** with no keys.
*
* [Read the documentation for `P.object.empty` on GitHub](https://github.com/gvergnaud/ts-pattern#pobjectempty)
*
* @example
* match(value)
* .with(P.object.empty(), () => 'will match on empty objects')
*/
const emptyObject = <input>(): GuardExcludeP<input, object, never> => when(
(value) => value && typeof value === 'object' && Object.keys(value).length === 0,
gitsunmin marked this conversation as resolved.
Show resolved Hide resolved
);

const objectChainable = <pattern extends Matcher<any, any, any, any, any>>(
pattern: pattern
): ObjectChainable<pattern> =>
Object.assign(chainable(pattern), {
empty: () => objectChainable(intersection(pattern, emptyObject())),
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like chainable would be enough here, since you can't chain empty several times

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I'll change it to "chainable." If it's wrong, please "comment."

}) as any;

/**
* `P.object` is a wildcard pattern, matching any **object**.
* It lets you call methods like `.empty()`, `.and`, `.or` and `.select()`
* On structural patterns, like objects and arrays.
* [Read the documentation for `P.object` on GitHub](https://github.com/gvergnaud/ts-pattern#pobject-predicates)
*
* @example
* match(value)
* .with(P.object.empty(), () => 'will match on empty objects')
**/
export const object: ObjectChainable<any> = objectChainable(when(isObject));
27 changes: 26 additions & 1 deletion src/types/Pattern.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export type MatcherType =
| 'or'
| 'and'
| 'array'
| 'object'
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure a new pattern type is necessary here because both patterns you added are implemented with guards

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll erase "object".

| 'map'
| 'set'
| 'select'
Expand Down Expand Up @@ -97,6 +98,8 @@ export type CustomP<input, pattern, narrowedOrFn> = Matcher<

export type ArrayP<input, p> = Matcher<input, p, 'array'>;

export type ObjectP<input, p> = Matcher<input, p, 'object'>;

export type OptionalP<input, p> = Matcher<input, p, 'optional'>;

export type MapP<input, pkey, pvalue> = Matcher<input, [pkey, pvalue], 'map'>;
Expand Down Expand Up @@ -191,7 +194,6 @@ export type NullishPattern = Chainable<
GuardP<unknown, null | undefined>,
never
>;

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you remove this diff?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, I'll remove this diff

type MergeGuards<input, guard1, guard2> = [guard1, guard2] extends [
GuardExcludeP<any, infer narrowed1, infer excluded1>,
GuardExcludeP<any, infer narrowed2, infer excluded2>
Expand Down Expand Up @@ -658,3 +660,26 @@ export type ArrayChainable<
},
omitted
>;

export type ObjectChainable<
pattern,
omitted extends string = never
> = Chainable<pattern, omitted> &
Omit<
{
/**
* `.empty()` matches an empty object.
*
* [Read the documentation for `P.object.empty` on GitHub](https://github.com/gvergnaud/ts-pattern#pobjectempty)
*
* @example
* match(value)
* .with(P.object.empty(), () => 'empty object')
*/
empty<input>(): ObjectChainable<
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should just be Chainable here as well

ObjectP<input, Record<string, never>>,
omitted | 'empty'
>;
},
omitted
>;
80 changes: 80 additions & 0 deletions tests/object.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { Expect, Equal } from '../src/types/helpers';
import { P, match } from '../src';

describe('Object', () => {
it('should match exact object', () => {
const fn = () => 'hello';

const res = match({ str: fn() })
.with({ str: 'world' }, (obj) => {
type t = Expect<Equal<typeof obj, { str: 'world' }>>;
return obj.str;
})
.with(P.object, (obj) => {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add test covering how P.object behaves with more inputs:

  • Functions
  • Primitive values
  • Null

It should catch all values that are assignable to the object type, and type narrowing and exhaustive should both work

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added test. If you need more, please comment

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, functions and arrays are part of the object type in TypeScript: Playground

I think P.object should catch anything assignable to object to stay close to typescript semantics and play nicely with exhaustiveness checking.

I'm going to update your PR shortly

type t = Expect<Equal<typeof obj, {
readonly str: string;
}>>;
return 'not found';
})
.exhaustive();
expect(res).toEqual('not found');
});

it('should match object with nested objects', () => {
const res = match({ x: { y: 1 } })
.with({ x: { y: 1 } }, (obj) => {
type t = Expect<Equal<typeof obj, { readonly x: { readonly y: 1 } }>>;
return 'yes';
})
.with(P.object, (obj) => {
type t = Expect<Equal<typeof obj, never>>;
return 'no';
})
.exhaustive();
expect(res).toEqual('yes');
});

it('should match object with nested objects and arrays', () => {
const res = match({ x: { y: [1] } })
.with({ x: { y: [1] } }, (obj) => {
type t = Expect<Equal<typeof obj, { x: { y: [1] } }>>;
return 'yes';
})
.with(P.object, (obj) => {
type t = Expect<Equal<typeof obj, { readonly x: { readonly y: readonly [1]}}>>;
return 'no';
})
.exhaustive();
expect(res).toEqual('yes');
});

it('should match empty object', () => {
const res = match({})
.with(P.object.empty(), (obj) => {
type t = Expect<Equal<typeof obj, {}>>;

return 'yes';
})
.with(P.object, (obj) => {
type t = Expect<Equal<typeof obj, never>>;

return 'no';
})
.exhaustive();
expect(res).toEqual('yes');
});

it('should match object with optional properties', () => {
const res = match({ x: 1 })
.with(P.object.empty(), (obj) => {
type t = Expect<Equal<typeof obj, { readonly x: 1; }>>;
return 'no';
})
.with(P.object, (obj) => {
type t = Expect<Equal<typeof obj, never>>;
return 'yes';
})
.exhaustive();
expect(res).toEqual('yes');
});
});