fix: object patterns no longer match array values#353
Open
chatman-media wants to merge 1 commit into
Open
Conversation
Arrays are objects in JavaScript, so `{}` would vacuously match any
array (including `[]`) because `Reflect.ownKeys({}).every(…)` returns
`true` for an empty key set.
Add an early `Array.isArray(value)` guard in `matchPattern` so that
a plain-object pattern is rejected when the value is an array.
Closes gvergnaud#309
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Arrays are objects in JavaScript, which means
typeof [] === 'object'. Because of this, when matching an array value against an object pattern like{}, the runtime matcher entered the object-pattern branch and calledReflect.ownKeys({}).every(…). Sinceeveryon an empty iterable always returnstrue, any array — including[]— matched the empty object pattern{}.Reported in #309.
Root cause
In
src/internals/helpers.ts,matchPatternchecksisObject(pattern)first, which is true for plain objects. Inside that block it checksArray.isArray(pattern)to handle tuple patterns, but it did not check whethervalueis an array before falling through to the plain-object key iteration:Fix
Add a single
Array.isArray(value)guard immediately before theReflect.ownKeysiteration so that a non-array pattern is rejected when the value happens to be an array:Test evidence
New test in
tests/objects.test.tsunderissue #309:match<any>([]).with({}, …)'matched object pattern''no match'match<any>([1,2,3]).with({}, …)'matched object pattern''no match'match<any>([1,2,3]).with({ length: 3 }, …)'matched object pattern''no match'match<any>({}).with({}, …)'matched'(correct)'matched'(still correct)match<any>({ a:1 }).with({ a:1 }, …)'matched'(correct)'matched'(still correct)Full suite: 454/454 tests pass after the fix.
Closes #309