typescript - 如何在对象中获取联合类型的类
问题描述
我有一个像这样的常量对象:
class A {}
class B {}
const X = {
a: A,
b: B
} as const
如何获得对象值的联合类型A | B
(不重复代码)?
例如,我想实现这一点:
// I need
type XUnion = A | B;
// so that this works
const bar: XUnion = new A();
我试过这样做,但它不起作用:
type XValues = typeof X[keyof typeof X];
// now XValues = typeof A | typeof B
const foo: XValues = new A();
// ^^^ compile error:
// Type 'A' is not assignable to type 'XValues'.
// Property 'prototype' is missing in type 'A' but required in type 'typeof B'.
解决方案
推荐阅读
- ruby-on-rails - ROR:参数数量错误(给定 2,预期 1)
- html - 引导程序中的导航栏列表对齐问题
- scala - 如何在 Scala 中实现 Levenshtein 距离算法
- angular - Angular routerLink 什么都不做并重定向到主页
- node.js - 不使用 await 异步函数的性能问题
- java - JPA - 辅助表映射方向
- class - 如何处理需要彼此工作的类?
- python - 如何使用 Elementtree python 删除结束标签?
- javascript - 在 onBlur 模式下使用 react-hook-form 启用/禁用提交按钮
- gremlin - Gremlin 找到顶点之间最轻的路径