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: added docs and test for P.object.exact(..) #244

Draft
wants to merge 5 commits into
base: gitsunmin/main
Choose a base branch
from
Draft
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
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1545,6 +1545,23 @@ console.log(isMatching(P.object.empty(), null)); // false
console.log(isMatching(P.object.empty(), undefined)); // false
```

### `P.object.exact({...})`

`P.object.exact({...})` matches objects that contain exactly the set of properties defined in the pattern.

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

const fn = (input: unknown) =>
match(input)
.with(P.object.exact({ a: P.any }), () => 'Objects with a single `a` key that contains anything.')
.otherwise(() => '❌');

console.log(fn({})); // ❌
console.log(fn({ a: 1 })); // ✅
console.log(fn({ a: 1, b: 2 })); // ❌
```

## Types

### `P.infer`
Expand Down
5 changes: 4 additions & 1 deletion src/patterns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -656,10 +656,13 @@ function isObject(x: unknown): x is object {
return !!x && (typeof x === 'object' || typeof x === 'function');
}

function hasExactKeys(keys: Set<PropertyKey>, x: unknown) {
function hasExactKeys(keys: Set<string>, x: unknown) {
if (!x || typeof x !== 'object') return false;
const xKeys = new Set(Object.keys(x));
if (Array.isArray(x)) return false;
if(xKeys.size !== keys.size) return false;
for (const key in x) if (!keys.has(key)) return false;
for (const key in keys) if (!xKeys.has(key)) return false;
return true;
}
JUSTIVE marked this conversation as resolved.
Show resolved Hide resolved

Expand Down
6 changes: 5 additions & 1 deletion src/types/Pattern.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,10 @@ export type ObjectLiteralPattern<a> =
}
| never;

export type ObjectExactPattern<a> = {
readonly [k in keyof a]: Pattern<a[k]>;
};
Comment on lines +174 to +176
Copy link
Owner

Choose a reason for hiding this comment

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

Is it to force people to include any key that exist's on an object? I think that makes a lot of sense, but how does it behave when the input has type unknown and any? Could you add tests for that?


type ArrayPattern<a> = a extends readonly (infer i)[]
? a extends readonly [any, ...any]
? { readonly [index in keyof a]: Pattern<a[index]> }
Expand Down Expand Up @@ -695,7 +699,7 @@ export type ObjectChainable<
* () => 'Objects with a single `a` key that contains anything.'
* )
*/
<input, const pattern extends ObjectLiteralPattern<input>>(
exact<input, const pattern extends ObjectExactPattern<input>>(
pattern: pattern
): Chainable<GuardExcludeP<input, InvertPattern<pattern, input>, never>>;
},
Expand Down
45 changes: 45 additions & 0 deletions tests/object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,4 +106,49 @@ describe('Object', () => {
expect(fn(null)).toEqual('no');
});
});

describe('P.object.exact({...})', () => {
it('should only catch exact match.', () => {
const fn = (input: object) =>
match(input)
.with(P.object.exact({ a: P.any }), (obj) => {
type t = Expect<Equal<typeof obj, { a: unknown }>>;
return 'yes';
})
.otherwise(() => 'no');

expect(fn({ a: [] })).toEqual('yes');
expect(fn({ a: null })).toEqual('yes');
expect(fn({ a: undefined })).toEqual('yes');
expect(fn({ a: 5 })).toEqual('yes');
expect(fn({ a: undefined, b: undefined })).toEqual('no');
expect(fn({})).toEqual('no');
expect(fn({ hello: 'world' })).toEqual('no');
expect(fn(() => {})).toEqual('no');
expect(fn([1, 2, 3])).toEqual('no');
expect(fn([])).toEqual('no');

const fn2 = (input: object) =>
match(input)
.with(P.object.exact({ a: { b: P.any } }), (obj) => {
type t = Expect<Equal<typeof obj, { a: { b: unknown } }>>;
return 'yes';
})
.otherwise(() => 'no');

expect(fn2({ a: { b: [] } })).toEqual('yes');
expect(fn2({ a: null })).toEqual('no');
expect(fn2({ a: { b: null } })).toEqual('yes');
expect(fn2({ a: undefined })).toEqual('no');
expect(fn2({ a: { b: undefined } })).toEqual('yes');
expect(fn2({ a: 5 })).toEqual('no');
expect(fn2({ a: { b: 5 } })).toEqual('yes');
expect(fn2({ a: undefined, b: undefined })).toEqual('no');
expect(fn2({})).toEqual('no');
expect(fn2({ hello: 'world' })).toEqual('no');
expect(fn2(() => {})).toEqual('no');
expect(fn2([1, 2, 3])).toEqual('no');
expect(fn2([])).toEqual('no');
});
});
});