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;
CodePudding user response:
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
}]
CodePudding user response:
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);