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

“空合并”TS友好函数

  •  2
  • None  · 技术社区  · 7 年前

    我正在尝试让一个“空合并函数”在TS中工作。 get(obj, 'key1', 'key2', 'key3')

    以下是我的资料:

    const X = {
        a: 42,
        b: 'bar',
        c: {
            d: 'foo'
        }
    }
    
    function get<T, K extends keyof T>(item: T, key: K, ...more: string[]): T[K] | null {
      if (key in item) {
        const out = item[key];
        if (more.length) {
          return get(out, more[0], ...more.slice(1));
        } else {
          return out;
        }
      } else {
        return null;
      }
    }
    
    const foo = get(X, 'c', 'd');
    

    这在顶层工作,例如 get(X, 'c') 但是由于某种原因,递归被破坏了,我不知道。无论我尝试什么,我都会得到各种各样的TS错误,或多或少地说,我无法将字符串 keyof T[K] 尽管这正是我第一次这么叫的!

    救命!

    [编辑]这很有效,但很难看!有人帮帮米耶

    function get<T, K extends keyof T>(item: T, key: K): T[K] | null;
    function get<T, K extends keyof T, L extends keyof T[K]>(item: T, key1: K, key2: L): T[K][L] | null;
    function get<T, K extends keyof T, L extends keyof T[K], M extends keyof T[K][L]>(item: T, key1: K, key2: L, key3: M): T[K][L][M] | null;
    function get(obj, key, ...moreKeys) {
      ...
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Justin Howard    7 年前

    目前在typescript中,不可能像您试图实现的那样表达深层次的类型路径。有一个GitHub问题 discussing possible workarounds 类似于你自己的。还有一个提议 suggesting the "pathof" keyword 为了解决这个确切的问题。

    同时,您似乎需要像在编辑中那样将类型完全定义为X级别。

    推荐文章