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


TypeScript: Lambdas and using 'this'

Question:

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?


Answer:

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
    f.call({});
}

new myScope();

To:

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

new myScope();

Related:


Using TypeScript type definitions with Webstorm 10 [duplicate]


node.js,typescript,webstorm
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 to declare knockout component in typescript?


javascript,knockout.js,typescript
I am trying to follow example to create a component in knockout. http://knockoutjs.com/documentation/component-overview.html 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) {...

Nested maps in Python 3


python,python-3.x,lambda
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...

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


c#,.net,generics,lambda
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...

How to do dynamic objects in TypeScript


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...

Mismatched anonymous define() in Chrome extension content script


google-chrome-extension,requirejs,typescript
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...

Inject dependency to the angularjs directive using typescript


angularjs,angularjs-directive,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...

List elements disappeared when I used a lambda expression or assignment


python,lambda
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...

Creating an Expression that returns an object


c#,.net,lambda,expression
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...

How to delete a row from database using lambda linq?


c#,android,linq,lambda
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 ==...

State in a java.util.function.Function


lambda,java-8,java-stream
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...

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


c#,.net,linq,lambda,clr
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...

converting List type with Lambda Java


java,lambda
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?...

Typescript file exporting interfaces comes up 404 using JSPM


typescript,typescript1.5,jspm,systemjs
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...

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


angularjs,typescript,angular2
I am going through the step by step tutorial on angular.io (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 can this be undefined in the constructor of an Angular config class?


angularjs,constructor,typescript,undefined,this
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...

Extending an interface from a third party definition file


typescript,sequelize.js
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...

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


c#,jquery,asp.net-mvc-4,lambda
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();...

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


node.js,visual-studio,typescript,jasmine,protractor
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...

Firebug does not display my JavaScript files


typescript,firebug
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...

Exception with type definition for random-string module


node.js,module,typescript
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...

Expression Lambda with types known at runtime


c#,lambda,expression-trees
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...

Instance of Show for Lambda


haskell,lambda,instance,show,typeclass
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...

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


entity-framework,unit-testing,lambda,moq
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...

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


typescript,vscode
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...

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


c#,linq,lambda,expression
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...

java 8 fuction invocation


java,lambda,functional-interface
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) ->...

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


visual-studio-2013,configuration,typescript,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...

How to compile TypeScript without using any references whatsoever


javascript,angularjs,typescript,tsd
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...

Java 8 map to only value type collection


java,lambda,java-8,collectors
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: https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html 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...

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


c++,c++11,lambda,assert,sizeof
Based on advice in http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/ 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,...

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


c#,lambda,anonymous-function
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); ...

Mapping a list to Map Java 8 stream and groupingBy


java,collections,lambda,java-8
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 call a lambda using LINQ expression trees in C# / .NET


c#,.net,linq,lambda,expression-trees
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)'...

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


c++,c++11,lambda
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 can I simulate a nested function without lambda expressions in C++11?


c++,function,c++11,lambda,allegro
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)); app.run(); return 0; } And I get the following error: ||=== Build: Debug in Joy-Plus-Plus (compiler:...

Dynamic lambda wrapped with try catch


c#,linq,dynamic,lambda
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...

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


javascript,jquery,typescript
Greetings fellow Earthicans, The following code is used on my website: brianjenkins94.me 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...

TypeScript 1.5 doesn't produce output


typescript
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...

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


java,lambda,java-8
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()) {...

construction of thread using lambda expression


multithreading,c++11,lambda,threadpool
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();...

Select the first object that match condition or an inner object


c#,lambda,ienumerable
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...

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


c#,linq,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=>...

C# lambda expressions without variable / parameter declaration?


c#,.net,linq,lambda
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()); }...

Update Knockout Observable string in refresh function


javascript,knockout.js,typescript
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 =...

Casting a list of objects to another one


c#,linq,casting,lambda,dao
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...

TypeScript does not detect union type with an && operator


typescript
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"; ...

Test if an object conforms to an interface in TypeScript


testing,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 =...

How to use lambda expression to call the comparator?


java,lambda,java-8
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:...

Sublime 3 JS Snippets to Typescript


javascript,typescript,sublimetext3,code-snippets
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...