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 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
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
44 changes: 44 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,40 @@ 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) => {
if (!isObject(value)) return false;

for (var prop in value) return false;
return true;
},
);

const objectChainable = <pattern extends Matcher<any, any, any, any, any>>(
pattern: pattern
): ObjectChainable<pattern> =>
Object.assign(chainable(pattern), {
empty: () => chainable(intersection(pattern, emptyObject())),
}) 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<GuardP<unknown, object>> = objectChainable(when(isObject));
25 changes: 25 additions & 0 deletions src/types/Pattern.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,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>;

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

export type MapP<input, pkey, pvalue> = Matcher<input, [pkey, pvalue], 'map'>;
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>(): Chainable<
GuardExcludeP<input, {}, never>,
omitted | 'empty'
>;
},
omitted
>;
143 changes: 143 additions & 0 deletions tests/object.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
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('when input is a Function, it should not match as an exact object', () => {
const fn = () => () => {};

const res = match(fn())
.with(P.object, (obj) => {
type t = Expect<Equal<typeof obj, () => void>>;
return 'not found';
})
.otherwise(() => 'not found');
expect(res).toEqual('not found');
})

it('when input is a Number (a primitive value), it should not be matched as an exact object', () => {
const fn = () => 1_000_000;

const res = match(fn())
.with(P.object, (obj) => {
type t = Expect<Equal<typeof obj, number>>;
return 'not found';
})
.otherwise(() => 'not found');
expect(res).toEqual('not found');
})

it('when input is a String (a primitive value), it should not be matched as an exact object', () => {
const fn = () => 'hello';

const res = match(fn())
.with(P.object, (obj) => {
type t = Expect<Equal<typeof obj, string>>;
return 'not found';
})
.otherwise(() => 'not found');
expect(res).toEqual('not found');
})

it('when input is a Boolean (a primitive value), it should not be matched as an exact object', () => {
const fn = () => true;

const res = match(fn())
.with(P.object, (obj) => {
type t = Expect<Equal<typeof obj, boolean>>;
return 'not found';
})
.otherwise(() => 'not found');
expect(res).toEqual('not found');
})

it('when input is Null, it should not be matched as an exact object', () => {
const fn = () => null;

const res = match(fn())
.with(P.object, (obj) => {
type t = Expect<Equal<typeof obj, null>>;
return 'not found';
})
.otherwise(() => 'not found');
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, {}>>;

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

it('should properly match an object against the P.object pattern, even 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, {
readonly x: 1;
}>>;
return 'yes';
})
.exhaustive();
expect(res).toEqual('yes');
});
});