【问题标题】:Get "values of" union elements in TypeScript?在 TypeScript 中获取联合元素的“值”?
【发布时间】:2020-04-12 23:05:16
【问题描述】:

给定联合类型:

type Valid = 'a' | 'b' | 'c'

可以提取吗?

const VALID_VALUES = valuesOf(Valid);
console.log(VALID_VALUES);
// ['a', 'b', 'c']

换句话说,与typeof相反

【问题讨论】:

    标签: typescript


    【解决方案1】:

    不,发出的代码中不存在类型,因此没有可以转换 VALID_VALUES 的源。

    不过,如果你想让事情变得干燥,你可以反过来做:

    const VALID_VALUES = ['a', 'b', 'c'] as const;
    type Valid = typeof VALID_VALUES[number];
    

    【讨论】:

      【解决方案2】:

      我会说是和否。有一种方法,但我不建议至少在运行时完全完成它,因为它会使您的程序变慢。可能会生成检查和构建时间所需的代码,因此您只需执行一次。

      一种解决方案是使用 TS Compiler API(有一个很好的 这个https://ts-morph.com/的包装器)

      import { Project, SyntaxKind } from "ts-morph";
      
      const project = new Project();
      const source = project.addSourceFileAtPath("src/api/valid-types.ts");
      const type = source.getFirstChildByKind(SyntaxKind.TypeAliasDeclaration);
      
      if (type) {
        const props = type
          .getType()
          .getUnionTypes()
          .map((t) => t.getText().slice(1, -1));
      
        console.log(props); // => ["a", "b", "c"]
      }
      

      这里列出了几个项目,并将这个想法提升到了一个新的水平

      【讨论】:

        猜你喜欢
        • 2019-04-03
        • 1970-01-01
        • 2020-02-16
        • 2022-12-31
        • 2021-10-12
        • 2022-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多