源代码
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];
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);
存在问题
- 函数的返回值是没有正确推导