Implementing nested functions in Angular2 with TypeScript

Currently in the process of migrating from Angular 1 to 2, encountering a situation with nested functions in JavaScript:

function normalizeDoc(doc, id) {
    function normalize(doc){...

After removing the "function" keyword, TypeScript errors have started to appear.

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


@Injectable()
export class PouchSeed {

    constructor(

    ) {
    }

    normalizeDoc(doc, id) {
        normalize(doc) {
            doc = angular.copy(doc);
            Object.keys(doc).forEach(function (prop) {
                var type = typeof doc[prop];
                if (type === 'object') {
                    doc[prop] = normalize(doc[prop]);
                } else if (type === 'function') {
                    doc[prop] = doc[prop].toString();
                }
            });
            return doc;
        };

        var output = normalize(doc);
        output._id = id || doc._id;
        output._rev = doc._rev;
        return output;
    };

The following errors are being encountered:

Typescript Error
';' expected.
src/providers/pouch-seed.ts
normalizeDoc(doc, id) {
    normalize(doc) {
        doc = angular.copy(doc);

Typescript Error
Cannot find name 'normalize'.
src/providers/pouch-seed.ts
normalizeDoc(doc, id) {
    normalize(doc) {

Typescript Error
Cannot find name 'angular'.
src/providers/pouch-seed.ts
normalize(doc) {
    doc = angular.copy(doc);

Questioning whether nesting methods like this is appropriate and seeking clarity on the reason behind the ";" error?

Answer №1

To enhance your compiler functionality, consider incorporating the es2016 and es2017 libraries into your project's tsconfig.json file:

  "compilerOptions": {
    "lib": [
      ..., "es2016", "es2017"
    ]
  }

This will allow you to utilize features such as Object Spread, Object.entries, and TypeScript deconstruction:

export class PouchSeed {

  constructor() { }

  normalizeDoc(doc, id) {
    const normalize = obj =>
      Object.entries(obj)
        .map(([key, value]) => ({
          [key]: typeof value === 'object' ? normalize(value) ? typeof value === 'function' : value.toString() : value
        }))
        .reduce((acc, value) => ({ ...acc, ...value }), {});
    return { ...normalize(doc), _id: id || doc._id, _rev: doc._rev };
  };
}

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

Error encountered in Typescript when handling fetch options as a variable

Why does this code compile perfectly? fetch('someurl', { method: 'GET', credentials:"same-origin" }) However, the following code throws a compilation error for fetch('someurl', init); const init = { method: &apo ...

What is the process for setting up custom global interfaces in TypeScript using .d.ts files?

I'm currently facing an issue in my ReactJS project using Webpack2 and TypeScript. Everything is functioning perfectly except for one thing - I've been struggling to move my self-written interfaces into separate files so they are accessible throu ...

What are the steps for changing this JavaScript file into TypeScript?

I'm currently in the process of converting this JavaScript file to TypeScript. However, I've encountered an error with the onClick function as shown below: import React from 'react'; import { Popover } from 'antd'; import A fr ...

How to dynamically change the title of a group box in Angular 8 using TypeScript

I am working with a component that includes a groupbox: <fieldset> <legend>Title</legend> </fieldset> Could I change the title of the groupbox using TypeScript code? ...

Troubleshooting issue with downloading files in Spring Boot and Angular 2

I've encountered an issue with downloading a file from Spring Boot using Angular2. The code snippet from Spring Boot originates from this Stack Overflow post about returning generated PDF using Spring MVC. Strangely, I can download the file directly ...

Retrieving Data from Angular Component within a Directive

Currently, I am in the process of creating an "autocomplete" directive for a project. The aim is to have the directive query the API and present a list of results for selection. A component with a modal containing a simple input box has been set up. The ob ...

UI components displaying varying data retrieved from Redux, despite having identical user interfaces

Currently, I have a component that receives data from the Redux store using useSelector. The UI remains the same, but I need to change where the data is coming from by passing the selector through props. My first question is: Is it acceptable to pass the ...

Demonstrating a feature in a custom Angular Material dialog box

I have a reusable custom Material UI Dialog that I want to utilize to show different components. For instance, I would like to display a Login component on one occasion and a Registration component on another. However, the issue arises when I assign my com ...

Typescript: Enhance your coding experience with intelligent parameter suggestions for functions

Within a nest.js service, there is a service method that takes an error code and generates a corresponding message to display to the user. The example below shows a simplified version of this method: getGenericErrorMessage(input: string): string { co ...

Incorrect positioning of AnyChart within a reusable component (Angular version 9.1.3, Bootstrap 4.4.1, Anychart version 8.7.1) causing display issues on the DOM

I have created a test dashboard featuring two Bootstrap cards, each containing an Anychart column chart. The primary objective is to experiment with reusable components. For those interested, here is the code link on Stackblitz Upon running the code, my ...

Is it possible to add additional text to an input field without modifying its existing value?

I have a numerical input field labeled "days" that I want to add the text " days" to without altering the actual numerical value displayed. <input type="number" class="days" (keyup)="valueChanged($event)"/> Users should only be able to edit the num ...

Is there a way to enhance a generic parameter using another generic parameter in TypeScript?

I am struggling with repetitive code that involves a type with minor variations: import { ComponentPropsWithRef, ElementType } from "react"; interface PackshotPropsBase { a: string } interface PackshotPropsWeb { b: string } export type Ele ...

Angular: Validation triggered following ngModelChange event

I am dealing with an input field that has a customValidator called fooValidator. This custom validator checks if the input matches a specific regular expression: <form #contratForm="ngForm"> <input type="text" ...

Tips for customizing the appearance of ng-bootstrap accordion

Looking to enhance the appearance of ng-bootstrap accordion with some unique fade styling. Any suggestions on how to accomplish this? ...

"Having trouble finding the issue in my Angular 2 todo list that is preventing new items from showing

I am having trouble with my 'todo-list' where the new 'todo' is not being added without any errors in the console. I have checked my code in the component.ts file but cannot figure out why it's not working. Here is the code snippet ...

What is the reason behind Collection.bulkwrite() only writing a single document to the MongoDB database?

I have utilized ag-grid to create this grid, and my objective is to bulkwrite its data into my MongoDB database by clicking on the saveInformation button. https://i.sstatic.net/bbMN4.png app.component.ts saveInformation() { console.log('actio ...

Sorting by Date in JavaScript

My goal is to filter out the elements in an array that have a date (converted from string) greater than a specific date. _this.downloadData.forEach(_d => _d.LogTime = _d.LogTime.toString()); console.log(_this.downloadData.filter(x=>new Date(x.LogTi ...

Excluding a Navbar in Angular 2: What is the best way to hide the navbar on a

Within app.component.html, I always incorporate the navbar on every page with the following code: <app-navbar></app-navbar> Is there a way to omit the navbar from a specific page? ...

TypeORM Error: Trying to access property 'findOne' of an undefined object

I've been working on implementing TypeORM with Typescript, and I have encountered an issue while trying to create a service that extends the TypeORM repository: export class UserService extends Repository<User> { // ... other service methods ...

Encountering the issue of receiving "undefined" in node.js after submitting data from an Angular form

I am facing an issue where I am getting 'undefined' in the backend (node.js) when I submit data from angular forms, even though I have used body-parser to parse the incoming data. server.js const express= require("express"); const app= ...