Is there a way to create a function that can take an object (which is part of a union) with a specified path and return the value of the config
object for that specific path?
I've been attempting the following:
type Cat = {
config: {
meow: string;
};
};
type Dog = {
config: {
woof: string;
};
};
type Animal = Cat | Dog;
const getProperty = <T extends Animal>(obj: T, path: keyof T["config"]) => {
// I'm encountering an error at this stage:
// "Type 'keyof T["config"] cannot be used to index type '{ meow: string; } | { woof: string }'
return obj.config[path];
};
However, if I try implementing a similar function to access fields at the root level (instead of within the config
object), it works without any issues:
type Cat = {
meow: string
}
type Dog = {
woof: string
}
type Animal = Cat | Dog
const getProperty = <T extends Animal>(obj: T, path: keyof T) => {
return obj[path]
}
I believe the problem lies in using keyof
on the object field of a Union type, but the exact reason eludes me.