代码之家  ›  专栏  ›  技术社区  ›  DonutReply

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

  •  0
  • DonutReply  · 技术社区  · 6 年前

    我想创建一个函数,您可以给出一个对象键的列表,它将导航通过您传递的对象上的那些键,并返回值或如果不存在,则不定义,并根据传入的对象的类型推断正确的类型。

    它的工作原理如下:

    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 回复  |  直到 6 年前
    推荐文章