Tips for updating property values when calling a TypeScript function

Hello everyone, I am looking to convert a snippet of JavaScript code into TypeScript.

JavaScript

function newState(name){
      var state ={
        name : name,
        age : 0
      } 
      return state
    }

function initStates() {  
 this.JamesState = newState('James')
 this.RoyState = newState('Roy');
 this.RoyState.age = 20;
}

TypeScript

newPRYState(name){
  let state = {
      name : name,
      age : 0
  }
  return state
}

initStates() { 
   this.JamesState = newState('James')
   this.RoyState = newPRYState('Roy');
   this.RoyState.age = 20; 
} 

Error: Type 'object' has no property 'age'

The desired outcome is: name: James age: 0 name: Roy age: 20

Please advise on how to resolve this issue.

Answer №1

In TypeScript, it is important to specify the type for all variables used in your code. This can be done by defining interfaces and assigning types to variables accordingly.

interface IState {
  name: string;
  age: number;
}

newPRYState(name: string): IState {
  let state: IState = {
      name : name,
      age : 0
  }
  return state;
}

initStates() { 
   this.JamesState: IState = newState('James')
   this.RoyState: IState = newState('Roy');
   this.RoyState.age = 20; 
} 

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

"Troubleshooting why React fails to update an array state

When I click the update name button, the state is not changing properly using setState. I want to update the persons variable and have it reflect in the DOM as well. Any ideas on how to achieve this? App.js import React, { Component } from "react"; impo ...

Ways to showcase multiple elements using introjs

I am attempting to highlight multiple DOM elements using the JS library intro.js, but I am encountering an issue. It seems that I can only define one element to be highlighted at a time. introjs.setOptions({ steps: [ { ...

Converting JSON to TypeScript in an Angular project

Within my Angular project, I have an HTTP service that communicates with a web API to retrieve JSON data. However, there is a discrepancy in the naming convention between the key in the JSON response (e.g., "Property" in uppercase) and the corresponding pr ...

When utilizing RxJS, the process of filtering Observable data may not function as expected if the filtering is carried out within a separate function rather than directly within the subscribe

While attempting to filter data from an external source using the RxJS filter on Observables, I encountered an issue where all records were returned instead of just the ones meeting the filtering criteria. This problem occurred when the code was within a l ...

Navigating with Angular 2: Expressing HTML 5 Routing Challenges

I'm currently working on a simple web application using Express 4 and Angular 2. The only Angular 2 specific aspect in this project is the utilization of its HTML5 router. Let me walk you through how the routing works in this app: There are two prim ...

rxjs in Angular2 is missing the observable.interval function

Currently, I am attempting to utilize the interval method of an observable; however, I consistently encounter the following error message: Property 'interval' does not exist on type 'Observable<any>'. I have included the follow ...

What is the best way to automatically show scrollbars when a page loads using JavaScript?

How can I make the vertical scrollbar appear as soon as the page loads using javascript? I am currently using a jquery slide toggle animation that causes the vertical scrollbar to show up because it makes the page longer. However, when the scrollbar appear ...

What could be causing the state to not update as anticipated?

I am currently in the process of developing a TicTacToe game and have a requirement to maintain the current player in state under the name currentPlayer. The idea is that after one player makes a move, I need to update currentPlayer to represent the opposi ...

What is the best way to navigate a dynamic table in Vue.js?

I'm currently working on creating dynamic tables in Vue using loops where users can upload a table and view it. <el-table :data="filtered" border style="width: 100%" height="500" @selection-change="handleSelectio ...

Trapped in the Google Maps labyrinth (Angular)

Hey there everyone! I'm currently working on an exciting angular application that integrates the Google Maps API. The goal is to create a feature that shows the 20 closest coffee shops based on the user's current location. However, I seem to be r ...

Guide on how to have two controllers execute identical tasks in Angular while modifying the appearance of the website

Trying to recreate Google's homepage functionality using Angular has been challenging for me. Despite watching Egghead videos and studying the API extensively, I couldn't find a specific example for this behavior. Here's what I aim to achiev ...

Utilizing Vue.js to add functionality for navigation buttons allowing users to move between survey questions

In my Vue.js component, I've written code to show survey questions in a mobile app for users. Here is a snippet of the code: <div class="col-12 p-0" v-for="( i, index ) in questions" :key="i"> <p cl ...

Steps for opening a clicked link in a new tab:

I have a link on my page that I would like to open in a new tab when clicked, but it doesn't seem to be working. Can anyone offer some suggestions or help? So far, I've tried the following code: <a target="_BLANK" ng-href="{{news.url ...

Learn how to collapse a list by clicking outside of it on the document with the following code: $(document).on("click"

I want to create a collapsible/expandable menu for my website. I had a version where hovering over a category would expand the subcategory, but what I really need is for the subcategories to expand when I click on a category and remain expanded until I cli ...

What is the best way to sort a union based on the existence or non-existence of a specific

My API response comes in the form of a IResponse, which can have different variations based on a URL search parameter. Here is how I plan to utilize it: const data1 = await request<E<"aaa">>('/api/data/1?type=aaa'); const d ...

The issue with the jQuery function lies in its inability to properly retrieve and return values

Within my code, I have a function that looks like this: $.fn.validate.checkValidationName = function(id) { $.post("PHP/submitButtonName.php", {checkValidation: id}, function(data) { if(data.returnValue === true) { name = true; } else { ...

Ways to update all URLs on a page with ajax functionality

My userscript is designed to modify the href of specific links on an IP-direct Google search page: // ==UserScript== // @name _Modify select Google search links // @include http://YOUR_SERVER.COM/YOUR_PATH/* // @include http://62.0.54.118/* // ==/Us ...

Is there a way to modify the window's location without having to reload it and without resorting to any sne

Initially, I believed that the hash hack was a necessity, but after observing the recent updates from Facebook, my perspective has shifted. The original hash hack (not certain if this is the correct term) involved changing location.hash to save a state in ...

What is the best way to limit a form to only allow 2 checkbox selections?

Seeking advice on implementing a form for a website giveaway featuring 3 prizes. Each participant should only be able to select 2 items from the list. I've already created a JavaScript-based form, but I'm concerned about its reliability since it ...

Click the link to find the JSON node that corresponds to the onclick event

After parsing JSON, the JS code below is returning a list of movie titles for me. Each movie title node contains additional attributes and values that are not currently being displayed. My goal is to have the other values in that specific node displayed wh ...