← 中文资源

简体中文版本

类型安全的点路径取值

用模板字面量类型解析 user.profile.city 与 user.roles.1 这类路径,返回精确的嵌套类型,并在运行时安全处理缺失路径。

阅读英文原文

题目

实现 getPath<T, P extends string>(source, path),其中 path 是点分隔的路径,例如 user.profile.city 或 user.roles.1。返回类型必须通过模板字面量推断出嵌套值类型:对象按键逐层深入,数组用数字段索引元素。运行时若路径不存在、数组越界或中途遇到原始值,应返回 undefined。示例输入包含文档和一组已知路径键,输出解析结果数组,缺失项用 null 表示。

解题思路

PathValue 先按第一个点把路径拆成 Head 与 Rest。如果 Head 是当前类型的键,就递归求 T[Head] 与 Rest 的值类型;如果当前类型是只读数组且 Head 是数字字符串,就递归求元素类型与 Rest;否则得到 never。最后一个路径段不再包含点时,同样先查键,再对数组做数字索引。getPath 的运行时逻辑与类型逻辑一一对应:数组要求规范数字索引且不越界,对象要求自有属性,其他情况立即返回 undefined。

参考实现要点

数字段在类型层用 ${number} 判断,在运行时用 /^(0|[1-9]\d*)$/ 校验,二者都排除了 01、-1 和前导加号。对象分支必须先排除 null,因为 typeof null 也是 object。使用 hasOwnProperty 避免原型链属性。代码中加入 Equal/Expect 类型断言,编译期即可验证 user.name 为 string、user.missing 为 never,而不需要运行测试。

常见错误

只处理对象键而忽略数组,user.roles.1 会被推断为 never,运行时也取不到值。运行时用 Number(key) 直接索引,会接受 1.5 或 01 等非规范段。类型层的数字判断写成 keyof T,字符串 “1” 不是数组的字符串键,结果仍然错误。把返回值断言成 any,会掩盖路径拼写错误。

验证方式

用 tsc –strict 编译,四个类型断言必须全部通过;把 user.name 改成 user.nam 应产生编译错误。运行样例并比对 values 数组。补充测试:roles 为空时索引 1 返回 null;路径经过 null 或数字时返回 null;索引写作 01 时返回 null。最后确认输出的对象值以 JSON 形式原样保留。

代码示例

declare const input: string;

type PathValue<T, P extends string> = P extends ''
  ? T
  : P extends `${infer Head}.${infer Rest}`
    ? Head extends keyof T
      ? PathValue<T[Head], Rest>
      : T extends readonly (infer Item)[]
        ? Head extends `${number}`
          ? PathValue<Item, Rest>
          : never
        : never
    : P extends keyof T
      ? T[P]
      : T extends readonly (infer Item)[]
        ? P extends `${number}`
          ? Item
          : never
        : never;

function getPath<T, P extends string>(source: T, path: P): PathValue<T, P> | undefined {
  let current: unknown = source;
  for (const key of path.split('.')) {
    if (current === null || typeof current !== 'object') return undefined;
    if (Array.isArray(current)) {
      if (!/^(0|[1-9]\d*)$/.test(key)) return undefined;
      const index = Number(key);
      if (index >= current.length) return undefined;
      current = current[index];
    } else {
      const record = current as Record<string, unknown>;
      if (!Object.prototype.hasOwnProperty.call(record, key)) return undefined;
      current = record[key];
    }
  }
  return current as PathValue<T, P> | undefined;
}

interface Doc {
  user: {
    name: string;
    roles: string[];
    profile: { city: string };
  };
}

const knownPaths = {
  name: 'user.name',
  role: 'user.roles.1',
  city: 'user.profile.city',
  profile: 'user.profile',
  missing: 'user.missing',
  absent: 'user.roles.5',
} as const;

type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2)
  ? true
  : false;
type Expect<T extends true> = T;
type NameIsString = Expect<Equal<PathValue<Doc, 'user.name'>, string>>;
type RoleIsString = Expect<Equal<PathValue<Doc, 'user.roles.1'>, string>>;
type MissingIsNever = Expect<Equal<PathValue<Doc, 'user.missing'>, never>>;
type ProfileIsObject = Expect<Equal<PathValue<Doc, 'user.profile'>, { city: string }>>;

interface Spec {
  doc: Doc;
  keys: Array<keyof typeof knownPaths>;
}

const spec = JSON.parse(input) as Spec;
const values = spec.keys.map((key) => getPath(spec.doc, knownPaths[key]) ?? null);
console.log(JSON.stringify({ values }));