简体   繁体   English

获取 TypeScript 中对象联合的键

[英]Get keys of union of objects in TypeScript

Is there a way to get all keys of type union type of objects { a: ...} | { b: ...}有没有办法获取对象的所有类型联合类型的键{ a: ...} | { b: ...} { a: ...} | { b: ...} ? { a: ...} | { b: ...} ? One thing worth mention — this type is generated dynamically.值得一提的是——这种类型是动态生成的。

Spent a few hours but without any luck...花了几个小时但没有任何运气......

Conditional types follow the distributive law .条件类型遵循分配律

Something along these lines (or at least a start)这些方面的东西(或至少是一个开始)

type Keys<T> = T extends {[key: string]: any} ? keyof T : never

type Test = Keys<{a: string} | {b: number} | {c: object}>

//type Test = "a" | "b" | "c"

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM