动态访问嵌套对象中的值时推断正确的类型

时间:2018-12-11 16:50:58

标签: typescript

我想创建一个可以提供对象键列表的函数,它将在您传递的对象上浏览这些键,并返回值或未定义的值(如果它不存在),并根据传入的对象的类型。

这是它应该如何工作的:

prop(['one', 'two', 'three'], {one: {two: {three: 'found it!'}}}) === 'found it!'
prop(['one', 'two', 'four'], {one: {two: {three: 'found it!'}}}) === undefined

我可以在这里专门用3个级别键入它,但最终希望它以任何合理的深度起作用。到目前为止,这是我到达的地方,see it with TS errors here

function prop<T, K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2]>(keys: [K1, K2, K3], obj: T) {
  // I don't think this type is right but can't find a way to get it to understand what level it's currently at
  let currentDepth: T | T[K1] | T[K1][K2] = obj;
  for (let i = 0; i < keys.length; i++) {
    const k = keys[i]
    currentDepth = currentDepth[k];
    if (i === keys.length - 1) {
      return currentDepth;
    }
    if (typeof currentDepth === 'undefined') {
      return currentDepth
    }
  }
  return undefined
}

关于是否可能或其他方法受到赞赏的任何暗示。谢谢

0 个答案:

没有答案