Underscore.JS: Access local variables and function inside each function of UnderscoreJS in Typescript

Standard

While using AngularJS with Typescript, I witnessed the scenario, where my function is accessing variables and functions defined in controller constructor, to make life easy for some collection manipulation, I used underscoreJS helper functions, _.each

_.each(data, function(item : any) {
     item.name = this.formatName(item);
});

Everything was on track, except I was unable to access local variables and functions(this.formatName) defined in the angular controller in underscoreJS _.each, I was getting an undefined error for this.formatName method inside _.each.

Solution:

As you are aware of the fact that ‘this‘ keyword behaves differently in JavaScript compared to other languages. For Typescript, ‘this‘ keyword refers to the current instance of the class. In JavaScript, the value of ‘this‘ is determined mostly by the invocation context of the function and where it is called. (Read this reference)

  1. In order to resolve this problem, inject ‘this‘ as context by setting it up as the third parameter to _.each helper function
_.each(data, function(item : any) {
     item.name = this.formatName(item);
}, this);

2. There is one more solution too by saving the context in temporary variable before consuming ‘this’ in _.each

public testFunction() : void {
  var context = this;
  _.each(data, function(item : any) {
      item.name = context.formatName(item);
  });
}

 

Advertisements

AngularJS: Error – Argument of type ‘RegExp’ is not assignable to parameter of type ‘string’

Standard

While working on a test project in AngularJS with Typescript, I came across this specific error:

Argument of type 'RegExp' is not assignable to parameter of type 'string'

Code:

let expression = new RegExp(/(test)=\(A:([0-9.]*)\)/g);

The problem is that I am duplicating the initialization process of Regex, first, it set up regular expression by standard syntax (/ /g) and then re-setup regular expression using constructor ( new RegExp() )

Solution 1:

let expression = /(test)=\(A:([0-9.]*)\)/g;

Solution 2:

let expression = new RegExp('(test)=\(A:([0-9.]*)\)', 'g');