My preferred method for accessing object properties is by using
const myproperty = 'name' as const;
type MyObject = {
name: string,
age: number;
}
let obj:MyObject = {name: 'Ryu', age:30};
const myproperty = 'name' as const;
console.log(obj[myproperty])
For instance, if you need to calculate the sum of the 'visited' property in a function called sum(), and then later calculate the sum of 'deals' using the same function, you can store all properties in an array and pass the index of this array as an argument to sum(0) or sum(1).
type Sale = {
id: number;
visited: number;
deals: number;
amount: number;
}
let data:Array<Sale> =[{id: 1, visited: 83, deals: 66, amount: 5501},
{id: 2, visited: 113, deals: 78, amount: 8290},
{id: 3, visited: 36, deals: 12, amount: 6096}]
const args = ['visited', 'deals', 'amount'] as const;
const sum = (property:number) => {
let total:number = 0;
data.forEach((element) => {
total += element[args[property]];
});
return total;
}
console.log(sum(0)) //Visited
console.log(sum(1)) //deals
console.log(sum(2)) //amount
Alternatively, you could utilize enum
for a more universal approach.
enum CategoryOfSum{
VISITED = 'visited',
DEDALS = 'deals',
AMOUNT = 'amount'
}
const sum = (type:CategoryOfSum) => {
let total:number = 0;
data.forEach((element) => {
total += element[type];
});
return total;
}
sum(CategoryOfSum.VISITED)
sum(CategoryOfSum.DEDALS)
sum(CategoryOfSum.AMOUNT)