Mastering Typescript: The ultimate guide to efficiently managing, storing, and retrieving Objects

Currently exploring typescript and aiming to construct a storage object.

The desired structure of the object is as follows:

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

I intend to maintain a log of past workouts while also having access to the most recent workout results when initiating a new session.

While experimenting with interfaces, I encountered an issue:

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);

    }

}

An error arises: Cannot read property 'push' of undefined.

Your guidance would be greatly appreciated :)

How can I effectively implement this data structure in typescript?

Answer №1

To properly set up your array, you need to initialize it either after declaration or in the constructor:

private workoutResults: Array<WorkoutResult> = [];

Alternatively, you can do it in the constructor like this:

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);

}

If you want to have sub arrays, consider using interfaces like so:

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

interface WorkoutRounds {
  rounds: WorkoutSet[];
}

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

You can then push complete objects containing this data into the WorkoutResults array.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Initiating change notification when utilizing service communication

So I am facing an issue with two unrelated components where I am attempting to establish communication between them using a service and a BehaviorSubject. Despite successfully exchanging data, calling the service from one component does not trigger change ...

CDK Drag and Drop capability for lists within lists

I am trying to figure out how to display users and their corresponding information in a structured way. Each user should be presented in their own column, with the associated information displayed within that column. I have been attempting to drag and drop ...

AngularJS bespoke provider leading to "Provider not found" error

I am facing an issue with my custom provider in AngularJS that is supposed to handle global configurations for my application. Despite my efforts, I am unable to properly inject this provider as AngularJS keeps throwing an "Unknown provider" exception. Thi ...

Discovering the Error Message within the Error Object transmitted by NodeJS to Angular

When handling errors in Nodejs functions using a try/catch scope, an error may be returned in cases such as when the user doesn't exist or when the database is unreachable. The code snippet below demonstrates this scenario: router.delete('/delete ...

Error: Import statement cannot be used outside a module (@cucumber/cucumber) while using Node.JS, Playwright, and Cucumber framework

I encountered an issue while attempting to compile my Node.js code that is compliant with ECMAScript 6: $ npx cucumber-js --require features/step_definitions/steps.ts --exit import { Before, Given, When, Then } from "@cucumber/cucumber"; ^^^^^^ ...

AngularJS not responding to double quotes in encoded format

I'm utilizing ngInit to transfer variables from PHP to my Angular JS Controller. Sometimes, the passed string may include encoded '"' (Double quotes ") <div data-ng-controller="UserController" data-ng-init='init({"test":"&q ...

Expo background fetch initialized but not activated

During the development of my React Native app, I encountered the need to perform periodic background fetches from another server. To achieve this, I utilized two classes from Expo: import * as BackgroundFetch from 'expo-background-fetch'; import ...

When trying to use `slug.current` in the link href(`/product/${slug.current}`), it seems to be undefined. However, when I try to log it to the console, it is displaying correctly

import React from 'react'; import Link from 'next/link'; import { urlFor } from '../lib/clients'; const Product = ({ product: { image, name, slug, price } }) => { return ( <div> <Link href={`/product/ ...

What is the best way to implement Angular translation for multiple values in a typescript file, while also incorporating parameters?

this.snackBar.open( `Only files of size less than ${this.fileSizeAllowed}KB are allowed`, this.translate.instant('USER_REG.close'), { panelClass: 'errorSnackbar', ...

Guide to accessing a URL using location services

Struggling to use the <a href tag, I'm exploring an alternate solution. The idea is to trigger a URL using ng-click, and then reload the page with that specific URL. Here's my snippet of html: <li class="item" ng-click="go_to()"> & ...

Having trouble with ng-hide and ng-show not functioning when a radio button is clicked

There are 2 radio buttons and 2 views that should be displayed based on the selection. <input class="inptFileRadio" type="radio" name="test" value="1" checked><span> one</span> <input class="inptFileRadio" type="radio" name="test" ...

Resolving route data in Angular 2 and above

When retrieving data from an API in an Angular route resolver, I encountered a problem where if there was an error due to a stale token, I needed to refresh the token and then retry the API call. Below is the code snippet illustrating this scenario: impor ...

Limit function parameter types to object keys

Is it possible to constrain my function parameter to match the keys of an object? I want to achieve something similar to this: export const details = { x: { INFO_x: 'xxx' }, y: { I ...

How to send a Django form using Django REST framework and AngularJS

Feeling a bit lost on how to handle form processing with django, django-rest-framework, angularjs, and django-angular. By using traditional Django techniques, I can generate a model form in my view and pass it over to my template. With the help of django ...

Retrieve a single user using a query in the GraphQL platform

I've been struggling to create a GraphQL query in Express that retrieves only one user instead of all users every time. This is the query I'm using, incorporating TypeORM as my ORM: import { GraphQLList, GraphQLID } from 'graphql'; imp ...

Challenges with flex in AngularJS's Material Design layout

Having some trouble with setting the flex properties on my layout. For reference, here is a plunker link: http://embed.plnkr.co/0SrUp25FvT2PAsJDEwF3/preview <md-content flex layout="row" layout-align="center"> <div layout="column"> ...

AngularJS directive for handling email input with separate values for displaying the email and storing it in

I am looking for a way to automatically add a predefined suffix to an email input. For example, if my email address is: [email protected] The user should only have to enter the first part of the email, like "abc", and the suffix would be added automa ...

What is the best way to incorporate an automatic scroll to the following section on a single page website

My goal is to implement a feature that enables automatic scrolling between sections as the user scrolls up or down. The smooth transition should occur when the user reaches halfway through each section, seamlessly moving to the next screen on the same page ...

Avoid obtaining cookies within the TRPC environment

Recently, I've been setting up TRPC with Next.js and attempting to implement server-side rendering where I fetch user data before the page loads using the trpc.useQuery hook. However, I'm facing an issue where I cannot access the JWT token cookie ...

a feature in mongoose that automatically increments versions when creating a new document

Is it possible to set up an auto-increment feature for the versionKey (__v) field whenever a new document is created, or should I consider using a different field like 'version' in the schema? Here's an example of the schema used in my appl ...