在TypeScript

时间:2019-01-21 10:55:37

标签: typescript union-types

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

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']

提前谢谢!

1 个答案:

答案 0 :(得分:2)

无法从标准打字稿中的类型获取值(可能对此语言进行了一些非正式的扩展)

您可以获得的类型是所有kind的并集:

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 }); 
相关问题