菜鸟类型编程记-获取 Deep Value

126 阅读1分钟

源代码

type AddPrefix<Prefix, Keys = ""> = `${Prefix & string}.${Keys & string}`;

type GetSubObject<V, K> = AddPrefix<K, GetDeepValue<V>>;

type HandleKey<V, K> = V extends Record<string, any> ? GetSubObject<V, K> : K;

type GetDeepValue<V> = {
  [K in keyof V]: HandleKey<V[K], K>;
}[keyof V];


/**
 * 获取深层次的value
 * @param obj
 * @param key
 * @param path
 * @param length
 */
export function getDeepValue<T extends Record<string, any>>(
  obj: T,
  path: GetDeepValue<T>
): any {
  const _path: string = path as string;
  const { length } = _path;
  if (length === 0) return;
  if (_path.indexOf(".") === -1) return obj[_path];
  return _path.split(".").reduce((result, key) => {
    return result[key];
  }, obj);

存在问题

  1. 函数的返回值是没有正确推导