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.

TypescriptData Integrity

Code

typescriptsnippet
34 lines
// 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 hidden

Code 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

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.