What is causing TypeScript to compile and remove local variables in my Angular base controller?

I am trying to develop a base controller in Typescript/Angular for accessing form data, but I'm encountering an issue where the form member seems to be getting removed during compilation and is not present in the generated JavaScript code.

Could you please help me identify where I might be making a mistake?

Below is the snippet of my code:

export class FormController {

    form: ng.IFormController;

    constructor() {
    }

    showValidation(fieldName: string, errorType: string): boolean {
        var field = this.form[fieldName];
        var fieldError = typeof errorType === 'undefined' ? field.$invalid : field.$error[errorType];
        return !field.$pristine && fieldError;
    }

}}

export class ImplController extends FormController {

    constructor(private $state: ng.ui.IStateService) {
        super();
    }


    public validateField(): boolean {
        return this.showValidation('field-name', 'invalid');
    }

}

The resulting output in JS looks similar to this:

var FormController = (function () {
    function FormController() {
    }
    FormController.prototype.showValidation = function (fieldName, errorType) {
              ...
    };
    return FormController;
}());

Answer №1

When programming in TypeScript, properties declared outside of the constructor are specific to TypeScript and do not actually exist in JavaScript's language specification. They are mainly used to help TypeScript understand the properties of your class.

To illustrate this concept further, consider the following TypeScript code:

class TestClass {
    myString: string = "Hello";
    constructor(){}
}

If you compile this code using the TypeScript compiler with ES6 as the target, it will be transformed into:

class Tester {
    constructor() {
        this.myString = "Hello";
    }
}

However, if you do not initialize a value for your variable, the TypeScript compiler will remove it:

class TestClass {
    myString: string;
    constructor(){}
}

This code will transpile to:

class TestClass {
    constructor(){}
}

Additional Note

In response to your query, the error you are encountering is likely due to not assigning a value to your property, causing the TypeScript compiler to remove it. Simply assign it a value such as IFormController to avoid errors.

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

Utilizing variables in Angular service to make API calls

Currently, I am working on accessing the Google Books API. Initially, I was able to directly access it in my controller but now I want to follow best practices by moving the business logic into a directive. HTML <form ng-submit="search(data)"> < ...

I am facing an issue with my react-app where it compiles successfully without any errors, but it is not rendering any elements

JavaScript file to run with npm start: import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router } from 'react-router-dom'; import Routes from './routes'; ReactDOM.render( <R ...

What is limiting me from utilizing the entire Google Calendar feed?

I currently have a public Google Calendar set up. My goal is to retrieve appointment data in JSON format from this calendar. When I utilize the following URL https://www.google.com/calendar/feeds/{calendar_id}%40group.calendar.google.com/public/basic?alt ...

Include new options to the select box only if they are not already listed

I'm currently working on a situation where I need to transfer items from one select element to another, but only if they are not already in the second select: $('#srcSelect option:selected').appendTo('#dstSelect') My challenge is ...

The body parser is designed to efficiently parse and handle both gzip and json formatted HTTP POST request bodies

I've set up an API endpoint to manage http POST requests from a client. At the moment, I'm using Express framework and bodyParser to handle request bodies. What I need help with is configuring body-parser to effectively handle cases where request ...

Easily accessible jQuery tabs with the option to directly link to a specific tab

I currently have tabs set up on my webpage. The code for these tabs is as follows: $('ul#tabs li a').click(function(){ var id = $(this).attr('id'); var counter = 1; $("ul#tabs a.current").removeClass('cur ...

Tracking changes in real time and calculating the sum with AJAX, PHP, and MySQL for efficient processing

Initially, I kindly request you to read this until the end. I am in dire need of assistance with my problem as I have searched for solutions but still remain clueless. https://i.sstatic.net/DAb1q.png Referring to the image provided, the first 'Produ ...

leveraging the power of jquery colorbox to dynamically display an angularjs template

Routes are being used to render the body of a template, as shown below. The template loads without any issues at this point. Upon clicking a link within the rendered template (/templates/my-details), the goal is to trigger a colorbox popup and use another ...

Reactjs Router.push function does not behave as intended

I'm currently working with Reactjs and Next.js. I am experiencing an issue where the correct data is only displayed after refreshing the page instead of upon clicking, as intended. To solve this problem, I have attempted to use "router.push", but unfo ...

What is the best way to make a box modal function that displays a different image source than the one shown in the modal?

I'm looking to create a box modal that shows one image on the page, and then displays a different image in the popup when clicked. Here's what I currently have: <div class="row"> <div class="modal-image"><img id="myImg" src="http ...

"Alert in Javascript executing prematurely prior to initiating the function for sending a get request

private validateURL(url: string) { let isValid = false; this.$http.get(url).then( (data) => { console.log('success'); isValid = true; } ).catch( (reason) => { console. ...

Is there a way to set columns as initially hidden in MaterialTable?

I have a MaterialTable with many columns, and some of them are not always necessary to display. I am looking for a way to hide these columns unless the user specifically selects them. I attempted to use the hidden: true property in the column configuratio ...

The angular.json file contains a script and a styles property

After encountering issues with adding styles and scripts to my angular.json file, I discovered that neither Bootstrap nor other scripts were taking effect. It turns out there are two places where you can define scripts and styles in the angular.json file a ...

Changing the state of a form field to "dirty" using Angular.js programmatically

When updating fields on my form programmatically with a value, I want to set the field state to $dirty. However, trying $scope.myForm.username.$dirty = true; doesn't seem to have any effect. I noticed that there is a $setPristine method available to ...

Tips for adding an svg element to an existing svg using d3.js

Can another SVG be appended to an existing SVG parent using d3.js? I have tried using the 'svg:image' attribute, but unfortunately, I lose full control over the inner SVG child. The DOM node is created by d3, but it is not rendered, resulting i ...

How should one properly format an array of objects with elements that are different types of variations?

I am currently developing a versatile sorting module using TypeScript. This module will take in an array of data objects, along with a list of keys to sort by. Once the sorting process is complete, the array will be sorted based on the specified keys. To ...

Was anticipating 1 argument, however received 5 in TypeScript

When running the code in this part, I expected to receive 0-1 arguments but ended up getting 5 instead. Do you have any suggestions for a solution? Register() { let newUser = new User(this.registerForm.value, newUser.city =this.cityid, ...

Ways to interact with similar dynamic controls in Javascript

I have an aspx page with a Select box control: <select name="selViewPerPage" id="selViewPerPage" style="width:30px"> To ensure consistent styling across all browsers, I am replacing this html control with a dynamic select box using "selectBox.js". ...

How to retrieve the first option selected in Material-UI React?

Hey there! I am currently working with React Material UI select. I have a question - how can I set the first option of items as selected without triggering the onChange method? When I change an option, it triggers the onChange method and adds an attribut ...

Utilizing Google Closure Library with Angular 6

I am looking to integrate the google closure library into my angular 6 application. To achieve this, I have utilized the following commands: npm install google-closure-compiler and npm install google-closure-library. My application can be successfully co ...