Fargho Fargho - 3 months ago 18
TypeScript Question

Typescript: Best way to create, save and search Objects

iam new to typescript and want to create a storage object.

The Object should look like this:

workoutResults: array {
workoutResult {
dateOfWorkout: string
rounds: array {
sets:array {
repeats: number;
weight: number;
duration: number;
}
}
}
}


I want to create a history of all workouts in the past and also want to get the latest workout results when the user starts a new workout.

At i just play around with the interfaces, but for some reason this doesnt work:

interface WorkoutResult {
workoutDate: string;
workoutSet: WorkoutSet;
}

interface WorkoutSet {
}

export class WorkoutDoPage {

private workoutResults: Array<WorkoutResult>;

constructor(private nav: NavController, private navParams: NavParams, public exerciseData: ExerciseData) {

var testDate: any = new Date();

this.workoutResults.push(testDate);

console.log(this.workoutResults);

}

}


throws Error: Cannot read property 'push' of undefined

Maybe you can help me out a little bit :)

Whats the best way to archive a data structure like this in typescript?

Answer

You have to initialize your array after declaration or in constructor:

private workoutResults: Array<WorkoutResult> = [];

or

constructor(private nav: NavController, private navParams: NavParams, public exerciseData: ExerciseData) {

    var testDate: any = new Date();
    this.workoutResults = [];
    this.workoutResults.push(testDate);

    console.log(this.workoutResults);

}

For the sub arrays you can go with something like:

interface WorkoutSet {
  repeats: number;
  weight: number;
  duration: number;
}

interface WorkoutRounds {
  rounds: WorkoutSet[];
}

interface WorkoutResults {
  dateOfWorkout: string;
  rounds: WorkoutRounds[];
}
workoutResults: WorkoutResults[] = [];

And then push full objects that contain these data into the WorkoutResults array.