← 中文资源

简体中文版本

PropertyKey 统一约束字符串数字与符号键

用 PropertyKey 约束泛型键提取器,让分组与索引工具同时保留字符串、数字状态码和 unique symbol 键类型,不会退化成普通 string。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

200 paths: /health,/ready
labels: ok fallback hidden

实现说明

实际承担运算责任的是函数体 groupByPropertyKey,其余都是接线。 这个示例中仅有的重复出现在 for (const item of items) 里。

使用要点

  • 运行之前不需要往项目里加任何东西。
  • 直接运行文件,输出会带上标签,比如 200 paths:、labels:——输出的每一行都能指回产生它的那次调用。

常见问题

在一个没有任何依赖声明的空项目里能跑吗?

可以——空项目原样能跑,因为什么都不用声明。 文件在加载时定义 groupByPropertyKey。

核心语句

const byStatus = groupByPropertyKey(routes, (r) => r.status);
const buckets = new Map<K, T[]>();

代码示例

// 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]);