gvergnaud / ts-pattern

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

feat: added docs and test for P.object.exact(..) #244

Open JUSTIVE opened 7 months ago

JUSTIVE commented 7 months ago

adds docs, and tests for P.object.exact

Todos:

JUSTIVE commented 7 months ago

currently, {} could be caught by P.object.exact({a: P.any}) pattern.

JUSTIVE commented 7 months ago

fixed {} caught by {a:P.any}, but nested object pattern should be tested

JUSTIVE commented 7 months ago

during the implementation of this feature, I'm concerned about the following scenarios.

  1. nested object, but an exact match for the outer side, and less strict matching inside. (the other way, less strict matching outside and strict inside makes sense, but not this one.)
  2. recursive objects.

maybe we need to consider those cases first before implementing it.

gvergnaud commented 7 months ago

I was think that exact({ ... }) would only apply to the current level of nesting. If you want everything to be exact, then you need to nest exacts as well:

P.object.exact({
   // this object should only have a single `a` key
   a: {
      // this object must have at least a `b` key that's a string.
      b: P.string
   }
})

If you want everything to be exact you'd do:

 P.object.exact({
   a: P.object.exact({
      b: P.string
   })
})

Do you find a problem with that? What are the scenarios that worry you?

JUSTIVE commented 7 months ago

I think that behavior could easily cause misunderstanding. I thought exact should catch 'exact' object matching, not 'exact matching, but only single depth'. It's a bit ambiguous.

JUSTIVE commented 7 months ago

I'll keep implementing with single-depth match version(because it's a sub-spec of full-depth matching), but still not sure it's good design or not.