Skip to content

Commit 59d6eee

Browse files
committed
feat: added docs and test for P.object.exact(..)
1 parent 6cc4989 commit 59d6eee

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

README.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1545,6 +1545,23 @@ console.log(isMatching(P.object.empty(), null)); // false
15451545
console.log(isMatching(P.object.empty(), undefined)); // false
15461546
```
15471547

1548+
### `P.object.exact({...})`
1549+
1550+
`P.object.exact({...})` matches objects that contain exactly the set of defined in the pattern.
1551+
1552+
```ts
1553+
import { match, P } from 'ts-pattern';
1554+
1555+
const fn = (input: unknown) =>
1556+
match(input)
1557+
.with(P.object.exact({ a: P.any }), () => 'Objects with a single `a` key that contains anything.')
1558+
.otherwise(() => '');
1559+
1560+
console.log(fn({})); //
1561+
console.log(fn({ a: 1 })); //
1562+
console.log(fn({ a: 1, b: 2 })); //
1563+
```
1564+
15481565
## Types
15491566

15501567
### `P.infer`

src/types/Pattern.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -695,7 +695,7 @@ export type ObjectChainable<
695695
* () => 'Objects with a single `a` key that contains anything.'
696696
* )
697697
*/
698-
<input, const pattern extends ObjectLiteralPattern<input>>(
698+
exact<input, const pattern extends ObjectLiteralPattern<input>>(
699699
pattern: pattern
700700
): Chainable<GuardExcludeP<input, InvertPattern<pattern, input>, never>>;
701701
},

tests/object.test.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,4 +106,22 @@ describe('Object', () => {
106106
expect(fn(null)).toEqual('no');
107107
});
108108
});
109+
110+
describe('P.object.exact({...})', () => {
111+
it('should only catch the literal `{}`.', () => {
112+
const fn = (input: object) =>
113+
match(input)
114+
.with(P.object.exact({ a: P.any }), (obj) => {
115+
type t = Expect<Equal<typeof obj, { a: unknown }>>;
116+
return 'yes';
117+
})
118+
// @ts-expect-error: non empty object aren't caught
119+
.exhaustive();
120+
expect(fn({})).toEqual('yes');
121+
expect(() => fn({ hello: 'world' })).toThrow();
122+
expect(() => fn(() => {})).toThrow();
123+
expect(() => fn([1, 2, 3])).toThrow();
124+
expect(() => fn([])).toThrow();
125+
});
126+
});
109127
});

0 commit comments

Comments
 (0)