What could be causing my TypeScript object to appear as "undefined" when I try to log it?

I created a StackBlitz demo featuring a button that, when clicked, should pass a value to the controller. In the controller, there is a function designed to assign this value to an object. However, TypeScript seems to be indicating that the object is undefined and preventing me from assigning values to its properties.

In my attempt to resolve the issue, I referred to the TypeScript Handbook's section on object types:

person: { name: string; age: number }

What I anticipated seeing in the console output was:

Button clicked!
42
{ foo: undefined; bar: undefined }
{ foo: 42; bar: true }

However, the actual output was:

Button clicked!
42
undefined
ERROR Error: cannot set property 'foo' of undefined

This deviation from expectations leaves me puzzled. Can anyone identify what might be causing this error?

The relevant code snippets are as follows:

app.component.html

<button (click)="clickMe(42)">Click me!</button>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
})
export class AppComponent  {
  myObject: { foo: number; bar: boolean };

  clickMe(value) {
    console.log("Button clicked!");
    console.log(value);
    console.log(this.myObject);
    this.myObject.foo = value;
    this.myObject.bar = true;
    console.log(this.myObject);
  }
}

https://i.sstatic.net/TgmYp.png

Answer №1

Your object currently lacks a defined value, as you have only specified its type without assigning any actual values. This is why you encounter errors when trying to assign values to its properties. To resolve this, you can initialize it within your constructor like this: this.myObject = { foo: null, bar: null }, or you may opt to set the properties as optional and initialize it simply as this.myObject = {}

It is generally recommended to allow TypeScript to infer the type whenever possible. In this scenario, instead of explicitly defining the type with a colon (:) notation, you could directly assign values to myObject like so: myObject = { foo: value, bar: value }. TypeScript will automatically infer the type while simultaneously assigning values.

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

Attempting to search for an item by its id within a local json file using Angular

I have a local JSON file containing Kitchen types. I created the KitchenTypesService with two functions inside, GET and FIND(ID). The GET function is working fine, but the FIND function is not working and displaying an error "ERROR TypeError: Unable to lif ...

Setting base URLs for production and development in Angular 6: A step-by-step guide

As a beginner in Angular, I am looking for a way to set different base URLs for production and development environments. I aim to dynamically configure the base URL to avoid hard-coding it in the index.html file every time I switch between these two enviro ...

How can I design a Typescript interface that accommodates both strings and other data types?

I am working on designing an interface that allows for an array of objects and strings to be stored. For instance: const array = [ '', {id: '', labels: ['']} ] I attempted to achieve this using the following code: export ...

Using React and TypeScript to pass member variables

My component Child has a member variable that can change dynamically. While I am aware of passing props and states, is there a more elegant solution than passing member variables through props or other parameters? class Child extends React.Component< ...

Using ngIf to validate an empty string in Angular 5

I need assistance with validating an empty string retrieved from a server Although it is usually straightforward, it's just not working as expected <div class="ui-g-2 info-txt" *ngIf="appointment.Notes !==null || appointment.Notes !== ...

Starting PM2 with multiple instances can be achieved by following these steps

While running my nodejs code with PM2, I encountered a requirement for multiple instances of nodejs executing the same code. To address this need, I created a script named "myscript.sh": cd ~/myproject PM2_HOME='.pm2_1' /usr/local/bin/node /u ...

Is there a way to recursively convert property types from one to another in an object that contains optional properties?

The scenario: I am currently working with MongoDB and a REST API that communicates using JSON. MongoDB uses objects instead of identifiers for documents, but when these objects are stringified (such as in a response body), they get converted into strings. ...

Declaring a custom Angular Pipe

I've created a custom Pipe to filter a list of items and integrate it into my Angular/Ionic application. // pipes/my-custom-filter/my-custom-filter.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'myCustomFilt ...

Validation of identification numbers in South Africa

Despite doing thorough research, I am unable to make the code work. South African ID numbers contain information about the individual's date of birth and gender. My goal is to extract this information and validate it when a user enters their ID number ...

Utilizing properties from the same object based on certain conditions

Here's a perplexing query that's been on my mind lately. I have this object with all the styles I need to apply to an element in my React app. const LinkStyle = { textDecoration : 'none', color : 'rgba(58, 62, 65, 1)', ...

Angular is able to successfully retrieve the current route when it is defined, but

Here's the code snippet I am working with: import { Router } from '@angular/router'; Following that, in my constructor: constructor(router: Router) { console.log(this.router.url); } Upon loading the page, it initially shows the URL a ...

Encountering a WriteableDraft error in Redux when using Type Definitions in TypeScript

I'm facing a type Error that's confusing me This is the state type: export type Foo = { animals: { dogs?: Dogs[], cats?: Cats[], fishs?: Fishs[] }, animalQueue: (Dogs | Cats | Fishs)[] } Now, in a reducer I&a ...

Triggering ngSubmit function when button is clicked inside an Ionic alert

My ionic app is up and running, utilizing a template driven form in Angular to gather user input. I'm using ngSubmit to pass this data to my ts.file. My challenge lies in triggering the ngSubmit function through a 'No and save data' button w ...

Unable to spy on the second and third call using Jest

I'm having trouble using spyOn on the second and third calls of a function in my jest test I attempted to follow the documentation with this approach: it("should succeed after retry on first attempt failure", async () => { jest.spyOn(n ...

issue with duplicating DOM element using function

My situation is unique from the one described in this post. The code mentioned there is not functioning as expected when clicking the clone button. I have even provided a video explanation of how that code works. Unfortunately, I haven't received any ...

Navigating Json List data in Angular 6: A simple guide

I have received the following response from a service, which I can see in the console but am unable to iterate through. { "input": { "personId": "0519769867" }, "output": { "error": null, "customerName": "ANDERSON, JACQ ...

Incorporating an external SVG file into an Angular project and enhancing a particular SVG element within the SVG with an Angular Material Tooltip, all from a TypeScript file

Parts of the angular code that are specific |SVG File| <svg version="1.0" xmlns="http://www.w3.org/2000/svg" width="950" height="450" viewBox="0 0 1280.000000 1119.000000" preserveAspectRatio= ...

What are the best ways to utilize @types/bootbox and @types/jquery?

Is there a way to incorporate @types/bootbox and @types/jquery into an Angular 4 project? I attempted the following: npm install @types/bootbox and in my code, I am implementing it like so: import * as bootbox from 'bootbox'. However, I encou ...

Asynchronous handling of lifecycle hooks in TypeScript for Angular and Ionic applications

I'm intrigued by the idea of integrating TypeScript's async/await feature with lifecycle hooks. While this feature is undeniably convenient, I find myself wondering if it's considered acceptable to make lifecycle hooks asynchronous. After ...

imported classes from a module cannot be accessed within the same module

Here is some TypeScript code that I wrote: Within my module, I am importing a library called ts-events. import {SyncEvent} from 'ts-events' module MyModule{ export class MyService{ } } In the same module but in a different file, I'm ...