I’ve been putting in a lot of effort recently to find a way to access one property, say propA
, of a type or interface into another property of the same type or interface, say propB
, so that I can make a type inference that is dependent on the value of propA
.
Notice that discriminated unions wouldn’t work here, because the type of propA
is actually Record<string, any>
, i.e., its keys are dynamic and not pre-defined. Unless there is something I’m missing.
Here is an example of what I had in mind:
type MyType = {
propA: Record<string, any>;
propB: keyof MyType["propA"]
}
const example: MyType = {
propA: {
name: "Jay",
age: 20,
},
propB: "name" // must be either "name" or "age"
}
Is it even possible?
Muhammad Maher Elsherif is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1