typescript - 在 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']
.
先感谢您!
解决方案
没有办法从标准打字稿中的类型获取值(可能有一些非官方的语言扩展允许这样做)
你可以得到一个类型,它是所有kind
s 的并集:
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 });
推荐阅读
- html - 如何让我的 Bootstrap 4 列填满整个行宽?
- java-8 - Java 8 中的编译器错误,Java 6 中没有错误,为什么?
- javascript - 如何从对象数组创建 JavaScript 对象?
- azure-active-directory - 如何在 Azure Active DIrectory 中组织或分组应用注册?
- docker - Docker - Xdebug 调试 PHP CLI 脚本(VS 代码)
- javascript - 如何使用 public/ 目录中的文件(如果存在)或使用其他文件(如果它不在我的反应应用程序中)?
- flutter - Flutter 从另一个 Widget 更改容器宽度
- sql - sql 注入 - SELECT 的风险
- android - RecyclerView 滚动到特定位置时初始动画不起作用
- php - 如何替换 woocommerce_product_tax_class 已弃用的钩子?