Similar to Typescript: Type of a property dependent on another property within the same object I want a type where the properties are dependent.
const attributes = {
physical: {
traits: {
strength: 1,
dexterity: 1,
stamina: 1,
}
},
social: {
traits: {
charisma: 1,
manipulation: 1,
appearance: 1,
}
},
mental: {
traits: {
perception: 1,
intelligence: 1,
wits: 1,
}
}
};
type AttributeTrait =
| {
category: 'physical';
trait: keyof typeof attributes.physical.traits;
}
| {
category: 'social';
trait: keyof typeof attributes.social.traits;
}
| {
category: 'mental';
trait: keyof typeof attributes.mental.traits;
};
const action: AttributeTrait = {
category: 'social',
trait: 'manipulation'
}
function increment(action: AttributeTrait) {
attributes[action.category].traits[action.trait]++; // error 7053
}
In the function, action.trait
is typed as:
(property) trait: "strength" | "dexterity" | "stamina" | "charisma" | "manipulation" | "appearance" | "perception" | "intelligence" | "wits"
so it can't be used to index traits
.
How can I solve this?