【问题标题】:How to get a set of string literals from a TypeScript union type? [duplicate]如何从 TypeScript 联合类型中获取一组字符串文字? [复制]
【发布时间】:2019-08-04 12:12:28
【问题描述】:

每当我在 TypeScript 中有一个联合类型的字符串时,我需要做的一件很常见的事情就是获取这些字符串文字的数组。

export type UserPersona =
    | "entrepreneur"
    | "programmer"
    | "designer"
    | "product_manager"
    | "marketing_sales"
    | "customer_support"
    | "operations_hr"

我觉得有点麻烦,但是每当我需要这样做时,我都会创建一个对象映射,将所有内容再次键入,然后获取可以转换类型的键。

const userPersonaMap: { [key in UserPersona]: true } = {
    entrepreneur: true,
    programmer: true,
    designer: true,
    product_manager: true,
    marketing_sales: true,
    customer_support: true,
    operations_hr: true,
}

export const userPersonas = Object.keys(userPersonaMap) as Array<UserPersona>

我不喜欢这种方法的几点:

  1. 我必须输入两次。
  2. 我必须转换类型。
  3. 存在运行时开销 - 理所当然,这是微不足道的,但我一直这样做

【问题讨论】:

  • 哦,是的。那就更好了!

标签: typescript


【解决方案1】:

这并没有直接回答问题,而是提供了不同的解决方案来获得相同的结果。

/**
 * Creates a string enum. Use like so:
 *     const Ab = strEnum(['a', 'b']);
 *     type AbKeys = keyof typeof Ab;
 * @param keys keys in the enum
 * @returns enum object
 */
export function createStringEnum<T extends string>(keys: T[]): {[K in T]: K} {
    return keys.reduce((res, key) => {
        res[key] = key;
        return res;
    }, Object.create(null));
}

const Ab = createStringEnum(['a', 'b']);
console.log(Object.keys(Ab)); // ['a','b']
console.log(Ab.a) // 'a'

type AbKeys = keyof typeof Ab;
const a: AbKeys = 'c'; // error

【讨论】:

    猜你喜欢
    • 2020-12-24
    • 2019-02-04
    • 2019-10-09
    • 2021-10-27
    • 2019-10-14
    • 2021-10-12
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    相关资源
    最近更新 更多