Skip to content

Commit

Permalink
Merge pull request #272 from Ayc0/symbol
Browse files Browse the repository at this point in the history
Symbols as keys
  • Loading branch information
gvergnaud authored Aug 8, 2024
2 parents 3f5978a + 7f2aaf3 commit e74557d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 14 deletions.
30 changes: 16 additions & 14 deletions src/internals/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,20 +103,22 @@ export const matchPattern = (
: false;
}

return Object.keys(pattern).every((k: string): boolean => {
// @ts-ignore
const subPattern = pattern[k];

return (
(k in value || isOptionalPattern(subPattern)) &&
matchPattern(
subPattern,
// @ts-ignore
value[k],
select
)
);
});
return (Object.keys(pattern) as Array<string | symbol>)
.concat(Object.getOwnPropertySymbols(pattern))
.every((k: string | symbol): boolean => {
// @ts-ignore
const subPattern = pattern[k];

return (
(k in value || isOptionalPattern(subPattern)) &&
matchPattern(
subPattern,
// @ts-ignore
value[k],
select
)
);
});
}

return Object.is(value, pattern);
Expand Down
28 changes: 28 additions & 0 deletions tests/objects.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { isMatching, P } from '../src';
import { Equal, Expect } from '../src/types/helpers';

describe('Objects', () => {
it('should work with symbols', () => {
const symbolA = Symbol('symbol-a');
const symbolB = Symbol('symbol-b');
const obj: { [symbolA]: { [symbolB]: 'foo' | 'bar' } } = {
[symbolA]: { [symbolB]: 'foo' },
};
if (isMatching({ [symbolA]: { [symbolB]: 'foo' } }, obj)) {
type t = Expect<Equal<typeof obj, { [symbolA]: { [symbolB]: 'foo' } }>>;
} else {
throw new Error('Expected obj to match the foo pattern!');
}
if (isMatching({ [symbolA]: { [symbolB]: 'bar' } }, obj)) {
type t = Expect<
Equal<
typeof obj,
{ [symbolA]: { [symbolB]: 'foo' } } & {
[symbolA]: { [symbolB]: 'bar' };
}
>
>;
throw new Error('Expected obj to not match the bar pattern!');
}
});
});

0 comments on commit e74557d

Please sign in to comment.