PropertyKey Covers String Number Symbol Keys
Constrain generic indexers with PropertyKey so helpers preserve string, numeric status code, and unique symbol keys instead of widening keys to string.
Code
// PropertyKey is the built-in union: string | number | symbol
function groupByPropertyKey<T, K extends PropertyKey>(
items: readonly T[],
pickKey: (item: T) => K,
): Map<K, T[]> {
const buckets = new Map<K, T[]>();
for (const item of items) {
const key = pickKey(item);
const list = buckets.get(key);
if (list) {
list.push(item);
} else {
buckets.set(key, [item]);
}
}
return buckets;
}
const internalTag = Symbol('internal');
const routes = [
{ status: 200 as const, path: '/health' },
{ status: 404 as const, path: '/missing' },
{ status: 200 as const, path: '/ready' },
];
const byStatus = groupByPropertyKey(routes, (r) => r.status);
const labels: Record<PropertyKey, string> = {
200: 'ok',
default: 'fallback',
[internalTag]: 'hidden',
};
console.log('200 paths:', byStatus.get(200)?.map((r) => r.path).join(','));
console.log('labels:', labels[200], labels.default, labels[internalTag]);Output
Captured from a sandboxed run of this snippet in the build pipeline.
200 paths: /health,/ready
labels: ok fallback hiddenCode mechanics — PropertyKey Covers String Number Symbol Keys
Structurally, expect the function groupByPropertyKey and nothing else.
The loop for (const item of items) is the only repeated construct.
What to watch for
- External surface stays empty since core stdlib APIs supply all behavior.
Using it
The demo output is labeled (200 paths:, labels:); each label names the call that printed it.
Key statements
const byStatus = groupByPropertyKey(routes, (r) => r.status);
const buckets = new Map<K, T[]>();
Interactive Tools for This Topic
Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Number FormatterFormat numbers with thousands grouping, fixed decimals, custom separators, and an optional prefix or suffix.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.Phone Number FormatterNormalize a phone number with an optional country code into E.164, RFC 3966, and grouped national formats, with digit-count validation.
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `groupByPropertyKey` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.