Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Symbols as keys #272

Merged
merged 3 commits into from
Aug 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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!');
}
Comment on lines +13 to +15
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test only wasn't enough as it was passing before (as it was stripping all symbols)

So I added the other if for the negative check

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!');
}
});
});