如何在不使用“字符串”索引的情况下将对象值转换为tumpecript联合?

发布于 2025-02-11 19:09:38 字数 360 浏览 2 评论 0原文

// from
const obj = {
  a: {
    aa: 'A',
    cc: 'C',
  },
  b: {
    bb: 'B',
    cc: 'C',
  }
} as const;

// to
type ObjValue = 'A' | 'B' | 'C';

嗨,我想从对象获得联合类型。

因此,我尝试使用typeof obj [keyOf obj typeof obj]模式,但它只是返回。

type ObjValue = 'C'

如何在没有字符串索引的情况下仅组成对象的字符串值?

// from
const obj = {
  a: {
    aa: 'A',
    cc: 'C',
  },
  b: {
    bb: 'B',
    cc: 'C',
  }
} as const;

// to
type ObjValue = 'A' | 'B' | 'C';

Hi, I want to get union type from object.

So I tried with typeof obj[keyof typeof obj] pattern, but it just returns this.

type ObjValue = 'C'

How do I get the union type composed only string values of object without String indexing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我不在是我 2025-02-18 19:09:38

我不确定为什么obj类型[keyOf obj typeof obj]模式实际上无法与工会合作。不过,使用映射类型可以解决问题。

type ObjValue = {
  [K in keyof typeof obj]: typeof obj[K][keyof (typeof obj[K])]  
}[keyof typeof obj]

// type ObjValue = "A" | "C" | "B"

I am not sure why the typeof obj[keyof typeof obj] pattern does not really work with unions. Using mapped types solves the problem though.

type ObjValue = {
  [K in keyof typeof obj]: typeof obj[K][keyof (typeof obj[K])]  
}[keyof typeof obj]

// type ObjValue = "A" | "C" | "B"

Playground

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文