gvergnaud / ts-pattern

🎨 The exhaustive Pattern Matching library for TypeScript, with smart type inference.
MIT License
12.51k stars 135 forks source link

Add P.object, P.object.empty and P.object.exact() #234

Open gvergnaud opened 8 months ago

gvergnaud commented 8 months ago

TODO

P.object predicates

P.object is itself a pattern, but also a module containing predicates related to object types.

P.object

P.object matches any value assignable to the object TypeScript type. This includes all object literals, but also arrays and functions!

P.object does not match primitive types, like strings or numbers.

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

const fn = (input: unknown) =>
  match(input)
    .with(P.object, () => '✅')
    .otherwise(() => '❌');

console.log(fn({})); // ✅
console.log(fn({ hello: 'world!' })); // ✅
console.log(fn([])); // ✅
console.log(fn(() => {})); // ✅

console.log(fn(1, true, 'hi')); // ❌ ❌ ❌

P.object.empty()

P.object.empty() matches the empty object {}:

import { isMatching, P } from 'ts-pattern';

console.log(isMatching(P.object.empty(), {})); // true

P.object.empty() does not match empty arrays, 0 values or nullish values:

import { isMatching, P } from 'ts-pattern';

console.log(isMatching(P.object.empty(), [])); // false
console.log(isMatching(P.object.empty(), 0)); // false
console.log(isMatching(P.object.empty(), null)); // false
console.log(isMatching(P.object.empty(), undefined)); // false
Lezzio commented 3 months ago

Very nice! Looking forward to using this new pattern