首页 > 解决方案 > 在 TypeScript 中映射标记联合类型的所有标签

问题描述

是否可以将标记联合类型的所有标记映射到数组中?假设我们有以下类型:

type Options = Cash | PayPal | CreditCard;    

interface Cash {
  kind: "cash";
}

interface PayPal {
  kind: "paypal";
  email: string;
}

interface CreditCard {
  kind: "credit";
  cardNumber: string;
  securityCode: string;
}

是否可以将所有鉴别器收集kind到一个字符串数组中?结果应该类似于['cash', 'paypal', 'credit'].

先感谢您!

标签: typescriptunion-types

解决方案


没有办法从标准打字稿中的类型获取值(可能有一些非官方的语言扩展允许这样做)

你可以得到一个类型,它是所有kinds 的并集:

type OptionsKind = Options['kind'] //  "cash" | "paypal" | "credit"

您还可以构建一个对象,该对象必须具有联合的所有属性并用于Object.keys从该对象获取数组:

type OptionsKind = Options['kind'] //  "cash" | "paypal" | "credit"
let OptionsKind: { [P in OptionsKind]: 1 } = {
    cash: 1,
    credit: 1,
    paypal: 1        
}
let OptionsKindArray = Object.keys(OptionsKind);

如果对象中有任何额外的键、对象中没有所有键以及任何键拼写错误,此解决方案将确保您收到错误。所以基本上它确保重复数据至少总是最新的。

你甚至可以为任何联合创建一个辅助函数:

type OptionKinds = Options['kind'] //  "cash" | "paypal" | "credit"
function unionValues<T extends string>(o: Record<T, 1>) {
    return Object.keys(o) as T[];
}

let OptionKinds = unionValues<OptionKinds>({ cash: 1, paypal: 1, credit: 1 }); 

推荐阅读