Sorry if the title sounds confusing. Essentially what I am trying to do is that I want to make a function that takes an object and a key of that object, where the key might be nested inside of the object and has to be a specific type specified in the generics. So like
type Key = {
key1: Key1;
};
type Key1 = {
key2: Key2;
};
type Key2 = {
status: Status;
};
type Status = "Active" | "Inactive";
interface MyObject {
key: Key;
}
const myObject: MyObject = {
key: {
key1: {
key2: {
status: "Active"
}
}
}
};
// 👇 this is the function I am trying to build
foo<MyObject, Status>(myObject, 'status')
Here I have a function foo, which takes two arguments. And the second argument is a key on the object(it could be nested so it is not necessarily on the initial level of the object) and it is of the type Status, in this case the key we can pass is status.
So if you change Status to Key2 then you can only pass key2 as the second argument because key2 is of the type Key2.
I am not sure if this is even possible with TypeScript. I guess I will need to do some sort of recursive generics but I am not exactly sure how to do it.