首页 > 解决方案 > 如何在对象中获取联合类型的类

问题描述

我有一个像这样的常量对象:

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

这是打字稿游乐场中示例的链接

标签: typescript

解决方案


编辑:

我找到了我们正在寻找的类型:InstanceType

type XValues = InstanceType<typeof X[keyof typeof X]>;

游乐场链接


推荐阅读