Skip to content

Commit

Permalink
feat: added docs and test for P.object.exact(..)
Browse files Browse the repository at this point in the history
  • Loading branch information
JUSTIVE committed Apr 7, 2024
1 parent 6cc4989 commit 59d6eee
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
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 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
2 changes: 1 addition & 1 deletion src/types/Pattern.ts
Original file line number Diff line number Diff line change
Expand Up @@ -695,7 +695,7 @@ export type ObjectChainable<
* () => 'Objects with a single `a` key that contains anything.'
* )
*/
<input, const pattern extends ObjectLiteralPattern<input>>(
exact<input, const pattern extends ObjectLiteralPattern<input>>(
pattern: pattern
): Chainable<GuardExcludeP<input, InvertPattern<pattern, input>, never>>;
},
Expand Down
18 changes: 18 additions & 0 deletions tests/object.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,4 +106,22 @@ describe('Object', () => {
expect(fn(null)).toEqual('no');
});
});

describe('P.object.exact({...})', () => {
it('should only catch the literal `{}`.', () => {
const fn = (input: object) =>
match(input)
.with(P.object.exact({ a: P.any }), (obj) => {
type t = Expect<Equal<typeof obj, { a: unknown }>>;
return 'yes';
})
// @ts-expect-error: non empty object aren't caught
.exhaustive();
expect(fn({})).toEqual('yes');
expect(() => fn({ hello: 'world' })).toThrow();
expect(() => fn(() => {})).toThrow();
expect(() => fn([1, 2, 3])).toThrow();
expect(() => fn([])).toThrow();
});
});
});

0 comments on commit 59d6eee

Please sign in to comment.