Is it possible to iterate over the keys of a sub object within a union type in TypeScript safely? The challenge is to accept this union in a function and process its sub object's keys without encountering any typing issues.
// TYPES
type A = {
bools: {
a: boolean;
b: boolean;
};
};
type B = {
bools: {
b: boolean;
c: boolean;
};
};
type U = A | B;
// ATTEMPTED TYPING
type GetKeyGroups<T> = T extends T ? Array<keyof T> : never;
type keygroups = GetKeyGroups<U['bools']>
// WANTED USE
const a: A = {
bools: {
a: false,
b: false,
},
};
const test = ( obj: U ) => {
const bools: U["bools"] = obj.bools
const keys = Object.keys(bools) as keygroups
keys.forEach((key) => console.log(bools[ key ]));
}
test(a)
Initially, this solution appeared promising until TypeScript flagged key
as type any in
keys.forEach((key) => console.log(bools[ key ]));
. Is there a workaround for this issue with the current version of TypeScript?