EzDev.org

TypeScript

TypeScript is a superset of JavaScript that compiles to clean JavaScript output. TypeScript - JavaScript that scales. typescript brings you optional static type-checking along with the latest ecmascript features.


@Directive v/s @Component in Angular

What is the difference between @Component and @Directive in Angular? Both of them seem to do the same task and have the same attributes.

What are the use cases and when to prefer one over another?


Source: (StackOverflow)

What is TypeScript and why would I use it in place of JavaScript? [closed]

Can you please describe what the TypeScript language is?

What can it do that JavaScript or available libraries cannot do, that would give me reason to consider it?


Source: (StackOverflow)

Difference between Constructor and ngOnInit

Angular provides life cycle hook ngOnInit by default. Could anyone tell me about the usage of ngOnInit if we already have a constructor?


Source: (StackOverflow)

get and set in TypeScript

I'm trying to create get and set method for a property:

private _name: string;

Name() {
    get:
    {
        return this._name;
    }
    set:
    {
        this._name = ???;
    }
}

What's the keyword to set a value?


Source: (StackOverflow)

Hide .js.map files in Visual Studio Code

I am working on a typescript project in Visual Studio code and would like to hide the .js.map (and maybe even the .js) files from appearing in the file explorer.

Is it possible to display only the .ts files in the file explorer?


Source: (StackOverflow)

TypeScript Converting a String to a number

Anyone a suggestion on how to convert a string to a number in TypeScript?

var aNumber : number = "1"; // --> Error

// Could this be done?
var defaultValue = 0;
var aNumber : number = "1".toInt32(defaultValue);

// Or ..
var defaultValue = 0;
var aNumber : number = StringToInt("1", defaultValue);

Update: I did some extra puzzling, the best sofar I've come up with: var aNumber : number = ( "1") * 1;

checking if a string is numeric is answered here: In Typescript, How to check if a string is Numeric.


Source: (StackOverflow)

TypeScript Objects as Dictionary types as in C#

I have some JavaScript code that uses objects as dictionaries; for example a 'person' object will hold a some personal details keyed off the email address.

var people = {<email> : <some personal data'>};

adding   > "people[<email>] = <data>;" 
getting  > "var data = people[<email>];" 
deleting > "delete people[<email>];"

Is it possible to describe this in Typescript? or do I have to use an Array?


Source: (StackOverflow)

Are strongly-typed functions as parameters possible in TypeScript?

In TypeScript I can declare a parameter of a function as a type Function. Is there a "type-safe" way of doing this that I am missing? For example, consider this:

class Foo {
    save(callback: Function) : void {
        //Do the save
        var result : number = 42; //We get a number from the save operation
        //Can I at compile-time ensure the callback accepts a single parameter of type number somehow?
        callback(result);
    }
}

var foo = new Foo();
var callback = (result: string) : void => {
    alert(result);
}
foo.save(callback);

The save callback is not type safe, I am giving it a callback function where the function's parameter is a string but I am passing it a number, and compiles with no errors. Can I make the result parameter in save a type-safe function?

tl;dr version: is there an equivalent of a .NET delegate in TypeScript?


Source: (StackOverflow)

Should I use typescript? or I can just use ES6? [closed]

My daily job is client developer using AngularJS. We are evaluating if we want to go with TypeScript. I did some research on typescript and almost every JavaScript package I need must have definition type files. I found that is not very convenient, especially if I would like to try something new and they don't have the definition for it. Its really frustrating. (Even the current jQuery definition gives me some problems if I want to use typescript 1.5 beta). I started looking at ES6 and it looks similar to TypeScript. Should I just use ES6 instead? Also, I heard angular 2 will have full support for TypeScript, will that be one reason I should stay with it?


Source: (StackOverflow)

How can I select an element in a component template?

Does anybody know how to get hold of an element defined in a component template? Polymer makes it really easy with the $ and $$.

I was just wondering how to go about it in Angular 2.

Take the example from the tutorial:

import {Component} from '@angular/core'

@Component({
    selector:'display'
    template:`
     <input #myname(input)="updateName(myname.value)"/>
     <p>My name : {{myName}}</p>
    `

})
export class DisplayComponent {
    myName: string = "Aman";
    updateName(input: String) {
        this.myName = input;
    }
}

How do I catch hold of a reference of the 'P' or 'input' element from within the class definition?


Source: (StackOverflow)

Angular 2 HTTP GET with TypeScript error http.get(...).map is not a function in [null]

I have a problem with HTTP in Angular 2.

I just want to GET a JSON list and show it in the view.

Service class

import {Injectable} from "angular2/core";
import {Hall} from "./hall";
import {Http} from "angular2/http";
@Injectable()
export class HallService {
    public http:Http;
    public static PATH:string = 'app/backend/'    

    constructor(http:Http) {
        this.http=http;
    }

    getHalls() {
           return this.http.get(HallService.PATH + 'hall.json').map((res:Response) => res.json());
    }
}

And in the HallListComponent I call the getHalls method from the service:

export class HallListComponent implements OnInit {
    public halls:Hall[];
    public _selectedId:number;

    constructor(private _router:Router,
                private _routeParams:RouteParams,
                private _service:HallService) {
        this._selectedId = +_routeParams.get('id');
    }

    ngOnInit() {
        this._service.getHalls().subscribe((halls:Hall[])=>{ 
            this.halls=halls;
        });
    }
}

However, I got an EXCEPTION:

TypeError: this.http.get(...).map is not a function in [null]

hall-center.component

import {Component} from "angular2/core";
import {RouterOutlet} from "angular2/router";
import {HallService} from "./hall.service";
import {RouteConfig} from "angular2/router";
import {HallListComponent} from "./hall-list.component";
import {HallDetailComponent} from "./hall-detail.component";
@Component({
    template:`
        <h2>my app</h2>
        <router-outlet></router-outlet>
    `,
    directives: [RouterOutlet],
    providers: [HallService]
})

@RouteConfig([
    {path: '/',         name: 'HallCenter', component:HallListComponent, useAsDefault:true},
    {path: '/hall-list', name: 'HallList', component:HallListComponent}
])

export class HallCenterComponent{}

app.component

import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES} from "angular2/router";
import {RouteConfig} from "angular2/router";
import {HallCenterComponent} from "./hall/hall-center.component";
@Component({
    selector: 'my-app',
    template: `
        <h1>Examenopdracht Factory</h1>
        <a [routerLink]="['HallCenter']">Hall overview</a>
        <router-outlet></router-outlet>
    `,
    directives: [ROUTER_DIRECTIVES]
})

@RouteConfig([
    {path: '/hall-center/...', name:'HallCenter',component:HallCenterComponent,useAsDefault:true}
])
export class AppComponent { }

tsconfig.json

{
  "compilerOptions": {
    "target": "ES5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules"
  ]
}

Sorry for the long post...


Source: (StackOverflow)

typescript getting error TS2304: cannot find name ' require'

I am trying to get my first Typescript and DefinitelyTyped node app up and running, and running into some errors.

I am getting the error "TS2304: Cannot find name 'require' " when I attempt to transpile a simple ts node page. I have read through several other occurrences of this error on SO and I do not think I have similar issues.
I am running at the shell prompt the command : tsc movie.server.model.ts. The contents of this file are:

'use strict';

/// <reference path="typings/tsd.d.ts" />

/*  movie.server.model.ts - definition of movie schema */

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var foo = 'test';

The error is thrown on the var mongoose=require('mongoose') line

The contents of the typings/tsd.d.ts file are:

/// <reference path="node/node.d.ts" />
/// <reference path="requirejs/require.d.ts" />

The .d.ts file references were placed in the appropriate folders and added to typings/tsd.d.ts by the commands:

tsd install node --save
tsd install require --save

The produced .js file seems to work fine, so I could ignore the error. But I would appreciate knowing why this error occurs and what I am doing wrong.


Source: (StackOverflow)

Angular2 - set headers for every request

I need to set some Authorization headers after the user has logged in, for every subsequent request.

Info:

To set headers for a particular request,

import {Headers} from 'angular2/http';
var headers = new Headers();
headers.append(headerName, value);

// HTTP POST using these headers
this.http.post(url, data, {
  headers: headers
})
// do something with the response

Reference

But it would be not be feasible to manually set request headers for every request in this way.

How do I set the headers set once the user has logged in, and also remove those headers on logout?


Source: (StackOverflow)

How do you explicitly set a new property on `window` in TypeScript?

I setup global namespaces for my objects by explicitly setting a property on window.

window.MyNamespace = window.MyNamespace || {};

TypeScript underlines MyNamespace and complains that:

The property 'MyNamespace' does not exist on value of type 'window' any"

I can make the code work by declaring MyNamespace as an ambient variable and dropping the window explicitness but I don't want to do that.

declare var MyNamespace: any;

MyNamespace = MyNamespace || {};

How can I keep window in there and make TypeScript happy?

As a side note I find it especially funny that TypeScript complains since it tells me that window is of type any which by definitely can contain anything.


Source: (StackOverflow)

Where can I find the TypeScript version installed in Visual Studio?

Maybe it's obvious, but I checked everywhere (besides the right place) and googled it. Nothing.


Source: (StackOverflow)