Error message indicating that the function is not defined within a custom class method

I successfully transformed an array of type A into an object with instances of the Person class. However, I'm facing an issue where I can't invoke methods of the Person class using the transformed array. Despite all console.log checks showing that everything was transformed correctly and b contains instances of the Person class rather than just arrays with data.

Below is the code snippet:

import crypto from "crypto"

type A = Array<[string, number, string]>;

type B = {
    [id: string]: Person
}

export class Person {
    _id: string; // must be unique
    age: number;
    name: string;
    city: string;

    constructor(name: string, age: number, city: string) {
        this._id = Person.generateUniqueID(12);
        this.age = age
        this.name = name
        this.city = city
    }

    private static generateUniqueID(len: number): string {
        return crypto.randomBytes(Math.ceil(len/2))
            .toString('hex')
            .slice(0, len);
    }

    public tellUsAboutYourself(): string {
        console.log(
            `Person with unique id = ${this._id} says:\n
             Hello! My name is ${this.name}. I was born in ${this.city}, ${this.age} years ago.`
        );
        return `Person with unique id = ${this._id} says:\n Hello! My name is ${this.name}. I was born in ${this.city}, ${this.age} years ago.`
    }
}

export const a: A = [
    ['name1', 24, 'city1'],
    ['name2', 33, 'city2'],
    ['name3', 61, 'city3'],
    ['name4', 60, 'city4']
];

export const b: B = a.reduce(function (value: any, [name, age, city]) {
    let persona = new Person(name, age, city);
    value[persona._id] = [persona.name, persona.age, persona.city]
    return value;
}, {});

a successfully transforms to b, console log for b looks like this:

{
  'd85750baf38f': [ 'name1', 24, 'city1' ],
  '1f8fc00c6762': [ 'name2', 33, 'city2' ],
  '8bac45ed719b': [ 'name3', 61, 'city3' ],
  '1f00fa9086a2': [ 'name4', 60, 'city4' ]
}

console log for Object.keys(b) is:

[ 'd85750baf38f', '1f8fc00c6762', '8bac45ed719b', '1f00fa9086a2' ]

so how come when I do:

Object.keys(b).forEach(key => {
    b[key].tellUsAboutYourself();
})

in tsc compiler it says:

    exports.b[key].tellUsAboutYourself();
                   ^

TypeError: exports.b[key].tellUsAboutYourself is not a function

Answer №1

Your object called `b` does not contain any instances of the `Person()` class. Instead, you are simply inserting non-method properties.

As shown below, each property in object `b` is just an array and does not have an actual object instance:

{
  'd85750baf38f': [ 'name1', 24, 'city1' ],
  '1f8fc00c6762': [ 'name2', 33, 'city2' ],
  '8bac45ed719b': [ 'name3', 61, 'city3' ],
  '1f00fa9086a2': [ 'name4', 60, 'city4' ]
}

To change this, you can convert each property of object `b` into a `Person` instance with the method `tellUsAboutYourself`, like so:

export const b: B = a.reduce(function (value: any, [name, age, city]) {
    let person = new Person(name, age, city);
    value[person._id] = person;
    return value;
}, {});

An alternate approach for your final loop could be utilizing Object.values(), allowing you to directly access the individual values :

Object.values(b).forEach(obj => {
    obj.tellUsAboutYourself();
})

Nevertheless, this suggestion aims at enhancing your code structure.

Answer №2

While working within the reduce function, it's important to note that assigning persona attributes to an array using "value[persona._id] = [persona.name, persona.age, persona.city]" does not save the entire Person object. This array lacks access to Person's methods. To preserve the complete Person object, you should instead use:

value[persona._id] = persona

This way, you retain all aspects of the Person object.

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

The pagination in React using React Query will only trigger a re-render when the window is in

Currently, I am utilizing React-Query with React and have encountered an issue with pagination. The component only renders when the window gains focus. This behavior is demonstrated in the video link below, https://i.sstatic.net/hIkFp.gif The video showc ...

Guide: "Adding markers to user-uploaded images - A step-by-step tutorial"

I'm struggling to create a website that allows users to upload images and use specific tools. However, I am facing an issue where the marker I want to add is appearing all over the webpage instead of just on the image itself. How can I confine it to o ...

JavaScript compilation failure: Unhandled SyntaxError: Unforeseen token '>' in string variable within an if statement -- Snowflake

Looks like there's an issue with JavaScript compilation. The error message reads: Uncaught SyntaxError: Unexpected token '>' in HP_SEARCHCBHMESSAGES at ' if (Fac123 <> "") ' position 1.. Strange how SF is not a ...

What is the best way to create a tree structure that can hold data from multiple sources?

I have a variety of Models within my application: ModelA: fields: [id, name], hasMany: ModelB ModelB: fields: [id, name, attr], hasMany: ModelC ModelC: fields: [id, name, attr] To efficiently manage this nested data, I utilize a data store in conjuncti ...

What issues are present with the JavaScript event management in this scenario? (Specifically using the click() and hover() jQuery functions)

Currently, I am in the process of developing a proof-of-concept for a project that mimics Firebug's inspector tool. For more detailed information, please refer to this linked question. You can view an example page of my work which has only been teste ...

To complete Mocha tests, ensure to use the done() method. However, keep in mind that the resolution method is too specific. Choose either to specify a callback *or* return a Promise, but not both simultaneously

Encountering a frustrating issue with a mocha test. When I leave it alone, it freezes and displays: Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. If I include `Pro ...

Click on the link within the Checkbox label on MUI

I am working on creating a checkbox for the "Terms of Use," using FormControlLabel to nest a Checkbox. However, I also need to include a link that opens a Dialog component displaying the terms. The challenge is that clicking on the link checks the checkbox ...

Fetching database entries upon page load instead of using the keyup function in JavaScript

Here is an HTML form input provided: <input type="text" id="username" value=""> In this scenario, when a username like "John" is entered and the enter button is pressed, the script below retrieves database records: $(function(){ //var socket = ...

Incorporate information into a React component

I'm currently working on my initial react component and facing a challenge while adding items to the parent element through an external click event. The user needs to select from a list of search results, and I intend for these selections to be incorp ...

Expanded MUI collapsible table squeezed into a single cell

I'm experimenting with using the MUI table along with Collapse to expand and collapse rows. However, I've noticed that when utilizing collapse, the expanded rows get squished into one cell. How can I adjust the alignment of the cells within the p ...

Using Ionic to invoke a function within another function in a JavaScript service

Hey everyone, I've come across an issue while working on my Ionic mobile app project. I need to call a function within another function in one of my service.js files (pushNotificationService.js). Here is the code snippet: checkForNewMessage: functi ...

Is there a way to eliminate the "Use different Apple ID" option when setting up Sign in with Apple on a Reactjs + React Native App?

Currently working on integrating Sign in with Apple into my React Native + Reactjs frontend stack. The challenge I am facing is wanting to eliminate the "Use a different Apple ID" option, similar to how Binance has achieved it in their implementation (fir ...

The function 'find' cannot be invoked on an undefined object

I'm currently working on implementing objects in my jQuery code. So far, I have the following: var options = { ul: $(this).find('.carousel'), li: options.ul.find('li') } The li property is causing an error - Cannot call meth ...

Error Encountered: AngularJS Form Email - SyntaxError: An unexpected token '<' was found in the code

My attempt to send an email from my AngularJS website involves the following setup: Contact.index.html: <form name="userForm" class="well form-search"> <input type="text" ng-model="name" class="input-medium search-query" placeholder="Name" ...

Prevent automatic scrolling to anchors when using router.push() in Next.js

When using the latest version 10.2 of next, every time a URL with a hash is pushed to the router, next.js automatically jumps to the anchor element. import {useRouter} from 'next/router' router.push('/contact#about-us'); This behavior ...

Incorporate a Custom Icon into NbSelect

I am currently utilizing Nebular in a project, where multiple dropdowns are being used as shown below: <nb-select fullWidth placeholder="Office" formControlName="office"> <nb-option value="Office_A"&bt;Office A</n ...

In JavaScript, there is a missing piece of logic when iterating through an array to find

I am working on a solution to populate empty values when data is not available for specific months. You can view my progress on Plunker here: http://plnkr.co/edit/f0IklkUfX8tkRZrn2enx?p=preview $scope.year = [ {"month":"mar", "val":"23"}, {"month":"feb", ...

What is the best way to update the context while iterating through a jQuery each loop?

I am currently working on a code snippet that preprocesses response data retrieved from an AJAX call before displaying it (note: the display part is not included in this snippet). Specifically, it updates the src attribute of the image within each li eleme ...

The use of fs.writeFileSync is invalid and will not work for this operation

Encountering an issue while working with fs in next.js, receiving the following error message: TypeError: fs.writeFileSync is not a function Here's a snippet from my package.json: resolve: { fallback: { "fs": false }, } ...

The autofocus feature on the textarea in Angular Material Dialog seems to be malfunctioning

Within a web app, I am utilizing the Dialog component from Angular Material. The Dialog consists of only a textarea that is initially empty. I aim to automatically focus on the textarea when the user opens the modal dialog. How can I achieve this? Despite ...