typescript,undefined,extending , Extending HTMLElement in TypeScript

Extending HTMLElement in TypeScript


Tag: typescript,undefined,extending

Im trying to extend the HTMLElement using TypeScript. Below is my code which alerts undefined because "this" returns a window object, which seems right. How can I access the calling HTMLElement in a similar fashion?

interface HTMLElement {
    setData(dataObject: any): void;

HTMLElement.prototype.setData = (dataObject: any) => {
        alert(this.id); //Undefined
        alert(this); //Window Object

var data = { "InHouse": "5", "BookedMtd": "105" }

Update: Got it to work by changing the code to:

HTMLElement.prototype.setData = function (dataObject: any): void {

Not sure what the difference is. I though It was the same.


That's because the lambda syntax you are using keeps the this value to the external this, by using a variable called _this, as you can see in the playground: http://past.is/wxBJm

Since the lambda is not in a class, it is bound to the "this" that is global, here the window object.

By using the function syntax, you keep the javascript behaviour, so this is bound to the object on the left hand side of the property access (dot notation).

But I think you should not add methods to a class using directly the prototype in typescript.


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

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

C# Rest API returns string with double quotes

I have this silly problem, which I hope someone could help me enlighten. I am building an extension for Umbraco7's backoffice, for that I need to receive a simple string. My problem is the string return from the REST api contain double quotes and then AngularJS wont model bind. Here's...

Use TypeScript lib.core.d.ts instead of lib.d.ts

It seems the TypeScript compiler always includes lib.d.ts or lib.es6.d.ts (depending on the compiler target). In our application we have a WebSocket class that is already defined in lib.d.ts. We're running our application under Node.js and not in a web browser, so we actually don't need all of the definitions...

Visual Studio 2015 RC + RequireJS + jQuery

I'm using Visual Studio 2015RC + Cordova CLI 5.1.1 + TypeScript + RequireJS + jQuery . I'd like to change the location of my jquery.js file from the scripts folder to scripts/lib. I added a requirejs.config and changed the jQuery location. requirejs.config({ baseUrl: 'scripts/lib', paths: { jquery: 'jquery' } });...

Pros & Cons of using requirejs (-m amd) for typescript+angular projects

For an angular 1.x project that uses typescript, what are the Pros and Cons of using AMD? Meaning, running tsc with the params -m amd and using requirejs, versus simply using the /// <reference path="..." /> for internal modules as well and wrapping in module(s). Which- Makes more sense for...

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: Lambdas and using '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?...

Setting dynamic properties with key from a private collection in TypeScript

Running this in the http://www.typescriptlang.org/Playground ... interface TestObj { name:String; } class Test { test; private myCollection:TestObj[] = []; private anyCollection:any[] = []; constructor() { var obj:any = {}; var refObj = {name:'prop'}; obj[refObj.name] = "This works!"; var collection:any[] = []; collection.push(refObj); this.test[collection[0].name] = "This works!"; this.myCollection.push(refObj); obj[this.anyCollection[0].name] = "This...

How to declare knockout component in 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) {...

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

TypeScript project organization, compile into a single JS file?

Recently I started working with TypeScript, using WebStorm IDE. Coming from a strong AS3 background I found TS a really good way to write JS, most of the concepts feel really familiar and convenient, but, when it comes to splitting classes,modules into separate files things starting to get really confusing....

What is the type of an object literal key as defined in TypeScript?

I'm not using TypeScript as the primary language for this application, but as the type-hinting assist for JetBrains' WebStorm alongside JSDocs. I'm also using the keyMirror utility to create quasi-enum object literals. Given the following: //enums.js var keyMirror = require('keyMirror'); module.exports = { CRUDVerbs: keyMirror({ //keymirror mirrors the key to...

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

is it possible to use TypeScript and Babel together

I am new to both TypeScript and Babel. I have researched both and found they have features the other does not have. I'd like get the best of both world by using TypeScript to organize my code then use babels ES6 features like asyc/await and others. Is this possible.

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

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

Undefined local variable post

I write this code: <% @user.posts.each do |post| %> <%= render 'post', locals: { post: post, user: @user} %> <% end %> Then in _post.htm.erb I write follow code: <div class="post-title"> <img src="<%= @user.avatar.url%>" class="img-rounded post-image"> <h4 id="post-name"><%= @user.first_name + ' ' [email protected]_name %> </h4> <div id="post-date"><%= post.created_at.strftime('%d %b -...

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

How to implement custom sort for koGrid?

Data: 16.00 hours 19.99 hours 210.46 hours 262.54 hours 303.19 hours 55.95 hours 60.07 hours 64.07 hours 7.95 hours What I want: I need to allow sorting for this king of data in koGrid (default feature by clicking grid header, asc or desc sort). Problem: The data is string so...

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

How to expose TypeScript modules in NodeJS?

I have a library that I'm building in TypeScript. I'd like to include this library in both TypeScript and JavaScript Node projects. What is the general strategy to do this? Should I compile and have two versions or is there some other strategy I should be using?

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

How to stop visual studio generate typescript js and js.map 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...

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

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

In JavaScript, is there any difference between typeof x == 'y' and typeof x === 'y'?

I'm aware of the difference between strict and loose comparison operators. Clearly x == y is different from x === y. But whenever I see code that uses typeof, it always uses ===. If the typeof operator always evaluates to a string (such as 'boolean', 'number', etc.), then wouldn't typeof...

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

Why does my .data function work in pieChart but not in lineChart in dc.js?

I want to plot data for a dimension that's not in crossfilter so I'm forced to use .data. All is fine for a pieChart, but when I switch to a lineChar I get the error p is undefined (Firefox) or Cannot read property y of undefined (Chrome). I tried following...

Namespace keyword in TypeScript

Trying to find out what does namespace keyword mean in TypeScript? Here's some reshuffle they've done recently to use namespace instead of module: https://github.com/Microsoft/TypeScript/commit/224e7630ea17c4547e97f85634f446b877955a67 In the absence of namespace spec, it looks like a rather pointless rename to make the language look C#-like. Or is there an obscure little difference...

How do I access the service provider when registering using typescript class

The following service provider registers successfully. Other controllers can use the service without trouble. My question is how to access the provider in order to configure it before the service is instantiated by the $injector service? module apiService{ export interface IBaseService{ leagueID: number; } export interface IApiBaseServiceProvider extends ng.IServiceProvider{ setLeagueID(leagueID:...

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

Angular with Typescript: HTTP Injector Factory vs. Service

I have created a Typescript Class (see code...) that I want to use as an HTTP injector. It is being added to the Angular module as a service (not a factory). I have noticed a few issues. When the class defines the 'request' and 'response' functions with capital letters, the...

Mocking Angular $window in unit test cases

I have been trying to unit test my angular custom service written in Typescript. The service reads a global variable defined on the Window object. I have made it promise, so that in future I can make a AJAX call to get this information. Here is my stripped down service:...

Angular 2/Typescript: require not found

I am trying to get the angular 2 example running with a gulp typescript compiler. The gulp-script compiles import {Component, View, bootstrap} from 'angular2/angular2'; to var angular2_1 = require("angular2/angular2") which does not run in the browser. What is wrong with this? As far as I know, this kind of implementation...

Module '“angular2/angular2”' has no exported member 'For'

hi I am following the tutorial on the official Angular2 website. https://angular.io/docs/js/latest/guide/displaying-data.html Here is my ts file /// <reference path="typings/angular2/angular2.d.ts" /> import {Component, View, bootstrap, For} from 'angular2/angular2'; @Component({ selector: 'display' }) @View({ template: '<p>name: {{myName}}</p>' + '<p>Friends:</p>' + '<ul>'+ '<li *for="#name of names">'+ '{{name}}'+ '<li>'+ '<ul>', directives: [For] })...

jquery $(this).attr('href') returns undefined

I've got a very simple code HTML <a class="qqPopupCTA" href="http://example.com">Button</a> JS $qqPopupCTA = $('.qqPopupCTA'); function showForm(e){ e.preventDefault(); var targetPageUrl = $(this).attr('href'); // do stuff } $qqPopupCTA.on('click', function(e){showForm(e);}); However I keep getting undefined href. Console.log($(this)) returns "window" and console.dir($(this)) returns "e.fn.init[1]" Any idea what am I doing wrong? The code is...

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

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

TypeScript: workaround for relative reference path?

My goal is to refer to .d.ts files that I've installed with tsd. The tsd definitions GitHub repository has examples using paths relative to the source file's location: /// <reference path="../typings/tsd.d.ts" /> I find that a potential maintenance issue - if I want to reorganize how my project is organized,...

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

When Using Typescript+angularjs the api result is not displaying in html

Below are my controller and html: When my make api call in controller i am storing the result in result variable, Now,that result variable when i am trying to print in html it is not printing anything, i have used one more variable name in controller that is printing in...

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

How to detect overflow HTML elements

I have created a navigation bar with div(s) within it. When i zoom-in, I hide the div's moving out of navigation bar through css [overflow:hidden]. My goal is to create a java-script variable which will tell me what all div's are out of navigation Bar( hidden because of overflow), as...

php array returns undefined but print_r shows otherwise [duplicate]

This question already has an answer here: PHP: “Notice: Undefined variable” and “Notice: Undefined index” 11 answers foreach($jsonmediationinfo as $value1) { echo $value1['mstatus']; print_r($jsonmediationinfo); } Output: 1Array ( [0] => Array ( [mstatus] => 1 [mhearingnum] => first [mminutes] => adakjaflafjlarjkelfkalfkd;la ) [1] => Array ( [mhearingnum] => second...

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

How to load System.js modules with TypeScript?

I'm trying to get TypeScript working with the default Aurelia skeleton, which is based on System.JS as a loader. I'm having trouble getting TypeScript to accept module imports. I renamed one of the skeleton files, "nav-bar.js" to "nav-bar.ts" to see if I could convert the example into TypeScript. The code...

“Undefined method PDO::execute()” despite using prepare

This code has been working before, but I recently added a database class. I get the instance and connection from it: $connection = MYSQLDatabase::getInstance()->getConnection(); $connection->prepare("INSERT INTO users etc etc....... $insertArray = $connection->execute(array( ":username" => $_POST["username"] )); getInstance() returns the database instance. getConnection() returns the connection property which contains: new PDO('mysql:host='...

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

Angular directive dependency injection - TypeScript

There seem to be a number of ways to create Angular directives in TypeScript. The neatest I've seen is to use a static factory function: module app { export class myDirective implements ng.IDirective { restrict: string = "E"; replace: boolean = true; templateUrl: string = "my-directive.html"; link: ng.IDirectiveLinkFn = (scope:...