How to access dynamically created properties of an object in typescript?

Issue

I want to sort an array of objects with dynamically created properties. In the code block below, you can see that there are two errors thrown by typescript when I try to access this new properties.

I could initiate increaseData with an initial 0, but it does not seem like a good solution. How would you handle something like this in typescript normally?

Quick fix

let myData = {
        "myProp" : 0
    }

Original Code

let myNum = 0;
let myArray = []
let myData = {}
/** Code in between...
 * - pushes myData objects with a new property into myArray.
 * - result e.g.:
 *      myArray [
 *          {myProp : 5},
 *          {myProp : 4},
 *          {myProp : 5},
 *           ...
 *      ]
 */


// When myArray is filled with myData elements I want to sort them by myProp
    // ERROR: Property 'myProp' does not exist on type '{}'
let sortedArray = myArray.sort((a, b)=> (a.myProp < b.myProp) ? 1 : -1)
    // ERROR: Property 'myProp' does not exist on type '{}'
let result = sortedArray[0].myProp;


Solution

It is possible by defining a type for your object that can take any string key.

// Defining type
type mytype = { [key:string]: number};

// Defining array of specified type
let myArray : mytype[] = [];

// Defining your object with specified type
let myData : mytype  = {}

// Adding objects with dynamic property in array 
myArray = [{myProp : 5},{myProp : 4},{myProp : 5}]

// Sorting the array
let sortedArray = myArray.sort((a, b)=> (a.myProp < b.myProp) ? 1 : -1)

// logging sorted array
console.log(sortedArray);


//output
[{
  "myProp": 5
}, {
  "myProp": 5
}, {
  "myProp": 4
}] 

Answered By – Shreekesh Murkar

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.