lambda,typescript,this , TypeScript: Lambdas and using 'this'

TypeScript: Lambdas and using 'this'


Tag: lambda,typescript,this

JavaScript frameworks often call callbacks using apply().

TypeScript's arrow notation, however, doesn't seem to allow me to access the 'this' pointer.

How's it done?

If it isn't, is there a place to down-vote the current 'this' handling on Lambdas?


TypeScript's handling of this in arrow functions is in line with ES6 (Read: Arrow Functions). Due to that specification, it would be inconsistent for it to act any other way.

If you want to access this of the current function, then you can use a regular function.

For example, change:

function myScope() {
    var f = () => console.log(this); // |this| is the instance of myScope{});

new myScope();


function myScope() {
    var f = function() { console.log(this); } // |this| is {}{});

new myScope();


How to declare knockout component in typescript?

I am trying to follow example to create a component in knockout. But I have to write a code in typescript. So how can I register component in knockout using typescript? What should I write in .ts file to convert it in something-like below. ko.components.register('like-widget', { viewModel: function(params) {...

Exception with type definition for random-string module

I am trying to write a .d.ts for random-string. I have this code: declare module "random-string" { export function randomString(opts?: Object): string; } I am able to import the module no problem then with: import randomString = require('random-string'); and invoke: console.log(randomString); // --> [Function: randomString] However, this doesn't work with...

Using TypeScript type definitions with Webstorm 10 [duplicate]

This question already has an answer here: intellisense and code complete for DefinitelyTyped (TypeScript type definitions) on WebStorm IDE 2 answers I am trying to use Webstorm 10's new built-in TypeScript compiler. When compiling a simple Node.js file such as below, it gives a TS compilation error of "Error:(1,...

How do I mock multiple levels of DbSet.Include lambdas?

I'm using Moq to write unit tests that use Entity Framework 6 DbSet and DbContext objects. I have a service method with a cascading/multi-level Include and I can't figure out how to set it up for testing. The service method looks something like this: return DataContext.Cars .Include(p => p.Model) .Include(p...

Extending an interface from a third party definition file

I'm using this definition file in my Typescript code. The problem is that, according to Sequelize documentation to set the length of a string column, I should define its type as: Sequelize.STRING(20) and the current definition file doesn't allow this. It allows only Sequelize.STRING (which makes a default column length...

Select the first object that match condition or an inner object

I have a class that contains an inner list of the same class, For example: class Foo { string SearchId; List<Foo> GroupedPackages } I want to return the first "foo" instance that fits a condition, it can be in the main instance or in the inner List. This is what...

Casting a list of objects to another one

I have the following classes(entities): Entity(base class, has 3 props) & Category(derives from Entity and adds some other props) The problem occurs when I read data from the DB(the fill method returns a list of Entities) and the compiler doesn't allow me to cast from Entity to Category. The problematic...

converting List type with Lambda Java

If I have an expression: / List<Long> / / List<String> / s.getPhones().addAll(Arrays.asList(rs.getString("phones").split(","))); Can I use Java Lambda to convert types with Long.parseLong in pritty form without "for loop" ? Or even if will use for loop, it will became more "codeless". How it must look like?...

Creating an Expression that returns an object

I have this method: public R TranslateExpression<R>(Expression exp) where R : DbRequest { //... } In another class I have the following method: public void Persist(E entity) { Expression expr = Expression.Return(entity); //Does not compile, but I'm looking for something like this PersistRequest request = TranslateExpression<PersistRequest>(expr); } How can I...

Use “Contains” to match part of string in lambda expression

I have this MVC page where I have three different "input" elements, all the same class, using the jQuery autocomplete. On any one of them I am doing this in the controller: [HttpGet] public ActionResult GetAllItemsEdit(string data, string source) { List<TextValuePair> items = InventoryControlRepository.GetAllItemsTVP(); var result1 = items.Where(item => item.Text.Contains(data.ToUpper())).ToList();...

List elements disappeared when I used a lambda expression or assignment

I'm just trying to figure out what is happening in this python code. I was trying to use this answer here, and so I was tinkering with the console and my list elements just vanished. What I was doing was loading the lines into a file into a list, then...

Inject dependency to the angularjs directive using typescript

Lets say I have a simple angular directive that looks like this: app.directive('setFocus', ['$timeout', function($timeout) { return { restrict: 'AC', link: function(_scope, _element) { $timeout(function() { _element[0].focus(); }, 0); } }; }]); How can I write this using Typescript and get the $timeout accesible within the link function? My example...

TypeScript does not detect union type with an && operator

In the below example x is actually a union type of 'boolean | string' but TypeScript considers it a string. Is this a bug or am I missing something? var x:string = false && "foo"; ...

How to do dynamic objects in TypeScript

Is there any way to define a dynamic object type in TypeScript? In the following example, I would like to define a type for "My Complex Type" by saying: Objects of type "My Complex Type" are objects having "any number of properties" but the values of those properties must be...

Instance of Show for Lambda

So, I have already defined the lambda data type as such: data LExpr = Variable String -- variable | Apply LExpr LExpr -- function application | Lambda String LExpr -- Lambda abstraction deriving (Eq, Show) Now I want to implement an instance of Show myself. I have already the function...

Dividing an Expression in C# using Expression.AndAlso() causes an Exception

On my project written in C#, I've found a HUGE predicate that is used in this method of linq : public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate); this predicate works perfectly, but it as so much condition that I struggled a lot before understanding it. I would like...

construction of thread using lambda expression

Can somebody explain where a thread is created on the lambda function below? What is the technique used? Can somebody recommend a reference to understand the semantics? I posted the full code now: class ThreadPool { public: ThreadPool(size_t); template<class F, class... Args> auto enqueue(F&& f, Args&&... args) ->std::future<typename std::result_of<F(Args...)>::type>; ~ThreadPool();...

Nested maps in Python 3

I want to transform my list list = [" a , 1 ", " b , 2 "] into a nested list [["a","1"],["b","2"]]. The following works: f1_a = map(lambda x :[t.strip() for t in x.split(',',1)],list) but this does not work with Python 3 (it does work with Python 2.7!): f1_b...

C# lambda expressions without variable / parameter declaration?

What's it called when a method that takes a lambda expression as the parameter, such as Enumerable.Where, is invoked without actually declaring a variable or method parameter in the expression? For example, I'm familiar with this lambda expression syntax: public string GetDigits(string input) { return new String(input.Where(i => Char.IsDigit(i)).ToArray()); }...

Mapping a list to Map Java 8 stream and groupingBy

I have this simple Bean class: public class Book { public Book(Map<String, String> attribute) { super(); this.attribute = attribute; } //key is isbn, val is author private Map<String, String> attribute; public Map<String, String> getAttribute() { return attribute; } public void setAttribute(Map<String, String> attribute) { this.attribute = attribute; } } In...

How to delete a row from database using lambda linq?

I want to perform a delete operation to unfriend a user in a certain android application I'm developing. The following method returns "Done" but the data doesn't delete from the table. What is the problem here? public string deleteFriend(int user, int friend) { int i = db.Friends.Where(x => x.Person.Id ==...

Typescript file exporting interfaces comes up 404 using JSPM

I'm using Typescript 1.5. I started using jspm. I have a few files that just consist of interface exports. In my tsconfig the module is set to 'system'. It seems to not like files that are just exporting interfaces. It's giving me 404 errors, looking for them in the dist/app...

java 8 fuction invocation

I have been using Java 8 from last couple of months and trying to get my head around lambdas. I have a quite bit understanding about concert. But struggling with custom functional interface execution as lambda call. If I create java Bifuctional interface implementation BiFunction<t1,t2,R> trade = (t1, t2) ->...

Node.d.ts issues errors using typescript compiler, how do I fix?

I have a project that's a NODE console application project using Visual Studio 2013. When I compile the solution I'm getting typescript errors as follows: Typescript wants a semicolon after export interface ReadableStream extends EventEmitter { readable: boolean; read(size?: number): string|Buffer; //Like this ----> read(size?: number): string;|Buffer; Which means I...

Dynamic lambda wrapped with try catch

I want to filter an IEnumerable<ModuleItem> by an Where calls defined by the user (so the expression is given by a String object) So far I am able to create my filters with DynamicLinq with this code Expression<Func<ModuleItem, bool>> expr = System.Linq.Dynamic.DynamicExpression.ParseLambda<ModuleItem, bool>(value, null); The problem is that the overall...

What is the correct tasks.json config for compiling typescript in Visual Studio Code?

Using Ctrl+Shift+B I added a default tasks.json file and uncommented the second task runner block. I have a typescript file in the root of the directory and a tsconfig.json. Everytime I compile I get 'error TS5023: Unknown compiler option 'p'. What is the correct definition to allow me to compile...

Why this anonymous method does not work while the lambda does?

I am learning anonymous methods, lambdas etc. and cannot find the reason why it does not work here: // this does not work MyDictionary.Keys.Where(delegate(string s) { s.Length == 5; }); // this works MyDictionary.Keys.Where(w => w.Length == 5); ...

Transforming a two-variable std::function to a single-variable one

I have a function which gets two values, x and y, and returns the result: std::function< double( double, double ) > mult = []( double x, double y){ return x*y; }; Now I want to get a single-variable function for a constant y. I have written the following code, but...

How to call a lambda using LINQ expression trees in C# / .NET

I want to use expression trees to dynamically create a method to call a lambda. The following code runs fine for the first call to the ComposeLambda function, but the second call fails with the following error message. Incorrect number of arguments supplied for call to method 'Int32 lambda_method(System.Runtime.CompilerServices.Closure, Int32)'...

Update Knockout Observable string in refresh function

The code is in typescript and I am trying to show current date time on page load and update that date time on refresh click. In .ts file string that shows date time is declared like this. asOfString: KnockoutObservable<string>; In the constructor it is being set like this, this.asOfString =...

“CLR detected an Invalid Program” when compiling a constructor for List

I'm running into a strange problem when compiling a lambda expression for a parameterless constructor into a delegate. It works for almost all types that I have tried. Only the List<> is producing a “CLR detected an Invalid Program”. A Collection<> or an inherited class from List<> would not present...

How can I simulate a nested function without lambda expressions in C++11?

I have the following code: int main(int argc, char **argv) { App app(800, 600); app.add_event_scene(Scene("Event Plot", event_plot)); Image x("sample.png"); struct foo { static void visual_plot() { x.draw(); } }; // Error. app.add_visual_scene(Scene("Visual Plot", foo::visual_plot));; return 0; } And I get the following error: ||=== Build: Debug in Joy-Plus-Plus (compiler:...

Expression Lambda with types known at runtime

I am trying to make some Expressions where I will be using a lambda to create two methods: a selector and condition. Simplified the usage is condition(selector(data)), but the intemediate type is only known at runtime. I have the following code which works as long as the intemediate type is...

Java 8 map to only value type collection

I want to convert my Map <K,V> into only a Set <V>. I could not find any example anywhere, including Oracle's documentation here: All I could go further is: myMap.entrySet().parallelStream(). filter((entry) -> entry.getKey().startsWith("a")) .collect(Collectors.toSet()); This returns a Set of Map.Entry. In this example it's Map<String, String> so I would...

Sublime 3 JS Snippets to Typescript

I have a lot of useful snippets on JS. Like cl for console.log(); or fn for function methodName (arguments) { // body... } However I can't use them on *.ts files. How can manage the snippets and complation for js to ts also. Thanks...

How can this be undefined in the constructor of an Angular config class?

I've found some examples online, where people create TypeScript config classes and pass them on to Angular. When I've tried it, I got the weird exception, that this was undefined. A closer look to the other implementations revealed, they only use the constructor, so, are those examples actually inherently wrong...

How to stop visual studio generate typescript js and files while publishing

I set up my project that combine javascript output into file to $(ProjectDir)dist\output.js and uncheck generate source maps. Tools -> Options -> Text Editor -> Typescript -> Project -> Automatically compile Typescript files which are not part of a project is unchecked as well. While building and running project from...

TypeScript 1.5 doesn't produce output

Using typescript 1.5 beta. I have the following problem: if there are errors (from typescript point of view) in .ts files, the output .js files aren't produced and previous output (if any) is erased. Is it a 1.5 beta limitation or didn't I understand the right way the phrase from...

State in a java.util.function.Function

Suppose that I have a class which implements java.util.function.Function. The Function needs to know about a start date and end date but these will be constant throughout the lifetime of the function. I'm considering implementing the Function with private final fields for the start and end dates, as the apply...

Trying to implement an object-oriented design model for a simple navbar using TypeScript

Greetings fellow Earthicans, The following code is used on my website: in order to handle baseline navigation functionality and while it was working previously I decided to leverage the class-based approach provided by the TypeScript Language in order to structure my code in a more readable fashion. In doing...

Mismatched anonymous define() in Chrome extension content script

I'm trying to build a Chrome extension with TypeScript. The setup is quite simple: In manifest.json { "permissions": [ "webRequest", "webRequestBlocking", "tabs", "storage", "http://*/", "https://*/*" ], "content_scripts": [ { "matches": [ "http://*/*", "https://*/*" ], "js": [ "scripts/require.js", "scripts/require-cs.js", "scripts/main.js", "scripts/contentscript.js" ], "run_at": "document_end", "all_frames": true }], } In model.ts: export...

Java 8: Filtering Map to List by person's status

I'm trying to filter a Map<Long, Person> people and return only the IDs of these people having a status of SUBSCRIBED in a List<Long>. Here is the code in the old-fashioned way: public List<Long> getSubscribedPeople() { final List<Long> subscribedPeople = new ArrayList<>(); for (final Map.Entry<Long, Person> entry : subscribedPeople.entrySet()) {...

linq max inside a “where” clause with an “and” condition too in lambda

I need to get a field with those conditions, my actual code in SQL is this: SELECT archivo, fechadiario FROM ri_diariodefotos WHERE [email protected] AND fechadiario = (SELECT MAX(fechadiario) FROM ri_diariodefotos WHERE [email protected]) I actually have this : RI_DiariodeFotos.Where(a=> a.Idproyecto == PROJECTID && a.Fechadiario == RI_DiariodeFotos .Where(x=> x.Idproyecto == PROJECTID) .OrderByDescending(x=>...

How to compose two lambdas of type “delegate” in c#

Lets assume we have defined two Lambdas. Func<TInput, TOutput> a = …; Func<TInput1, TInput2, TOutput> b = …; Now lets assume that we have some code that does not work with generics and receives these Lambdas as not further typed delegates. delegate da = a; delegate db = b; In...

Firebug does not display my JavaScript files

I am building a web application with AngularJS en typescript in VS2012. These TypeScript files are all compiled into JavaScript files and send to the client using Bundles (all options turned off, thus I'm sending all files individually). In Firebug HTML view I can see all my JavaScript files, but...

How best to prevent unused variable warnings in custom assert without sizeof?

Based on advice in I've been working with my own version of assert (called emp_assert) for a while now. As such, when NDEBUG is set, my assert looks like: #define emp_assert(EXPR) ((void) sizeof(EXPR) ) This definition assures that any variables in EXPR still count as "used" in the compiler,...

Test if an object conforms to an interface in TypeScript

If I have a plain-old JavaScript object and a TypeScript interface, how can I write a test that asserts object conforming to my interface? interface Person { name: string age?: number } describe('Person interface check', () => { it ('should conform to "Person" interface', () => { let obj1 =...

Cannot find external module 'angular2/angular2' - Angular2 w/ Typescript

I am going through the step by step tutorial on (Angular 2). I am using typescript. I get the following error when trying to compile: Cannot find external module 'angular2/angular2' using the watch command. main.ts import {Component, View, bootstrap} from 'angular2/angular2'; @Component({ selector: 'my-app' }) @View({ template: '<h1>My first...

How to use lambda expression to call the comparator?

I am doing the leetcode's largest Number problem. Here is the problem: Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. and there is a 5 lines C# code:...

How to compile TypeScript without using any references whatsoever

Forgive me if I misunderstand, but I thought that if I used a tsconfig.json file at my project root, then I would no longer need to use any ///<reference path="..." /> tags in order to make my code compile. Am I wrong? For example, I'm using AngularJS. My App.ts file...