'How to access dynamically created properties of an object in typescript?
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 1:[1]
declare a type that has that property myProp
type HasProp = {
myProp: number,
}
let myArray: HasProp[] = [];
// now Typescript will know that your array has object with `myProp` and it's a number
// note that pushing into that array must be for object with that prop already declared or else Typescript will point that out
// also note that each object with prop `myProp` is a valid object of type `HasProp`
myArray.sort((a, b)=> (a.myProp < b.myProp) ? 1 : -1);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hagai Kalinhoff |
