I am attempting to configure an object property by selecting its key using a computed key, via an enum, as shown in the code snippet below.
Unfortunately, solutions 1 and 2 are not functioning. These are the solutions I need to implement in my code because I have to assign a value to a key that is dynamically retrieved from an API call.
Interestingly, solutions 4 and 5 are working fine, indicating that solutions 1 and 2 could potentially work by reassigning property values with the dynamic key following a hard-coded property key.
This is because TypeScript accepts an arbitrary number of additional properties as long as you provide matching interface properties. However, I am puzzled as to why duplicated dynamic properties are working in solutions 4 and 5.
So, why are solutions 1 and 2 not working? What am I missing?
Thank you for your assistance.
interface Cat {
tail: boolean;
legs: Quadruped;
}
interface Quadruped {
totalNumber: number;
}
enum BodyParts {
TAIL = 'tail',
TOTAL_NUMBER = 'totalNumber'
}
let brokenArgo: Cat = { tail: true, legs: { totalNumber: 4 } };
let argo: Cat = { tail: true, legs: { totalNumber: 4 } };
argo.legs = null;
let TN = 'TOTAL_NUMBER';
let tn: BodyParts = BodyParts[TN];
// solution 1 = broken
brokenArgo.legs = { [tn]: 6 }
// solution 2 = broken
brokenArgo.legs = { [BodyParts[TN]]: 6 };
// solution 3 = working
argo.legs = { [BodyParts['TOTAL_NUMBER']]: 6 };
// solution 4 = working
argo.legs = {
totalNumber: 0,
[tn]: 6
};
// solution 5 = working
argo.legs = {
totalNumber: 0,
[BodyParts[TN]]: 6
};
You can observe the script above running in this Typescript playground