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

元素?我能做到吗?

  •  4
  • recursive  · 技术社区  · 7 年前

    以下是我想要实现的目标:

    const names = ["foo", "bar", "baz"];
    type NameType = elementof names;  // This is not valid TypeScript
    

    行为与此相同:

    type NameType = "foo" | "bar" | "baz";
    

    解决方案需要完成几件事。

    • 提供有序的可枚举字符串序列。
    • 将名称公开为字符串文字类型的可寻址并集。
    • 允许在没有冗余源代码编辑的情况下维护字符串。

    TypeScript能做到这一点吗?

    注: 这与 Convert string[] literal to string type literal ,因为这个问题不需要特定的字符串序列。联合类型不会在运行时生成任何获取订单信息的方法。

    1 回复  |  直到 5 年前
        1
  •  2
  •   Titian Cernicova-Dragomir    7 年前

    可以使用类型查询获取项目的类型:

    type NameType = typeof names[number];
    

    问题是 names string[] ,所以上面的代码只生成 string .

    可以推断 const 使用辅助函数。

    function array<T extends string>(p: T[]) : T[] {
      return p
    }
    
    const names = array(["foo", "bar", "baz"]);
    type NameType = typeof names[number];   // The same as "foo" | "bar" | "baz"