Showing posts with label TypeScript. Show all posts
Showing posts with label TypeScript. Show all posts

Thursday, May 15, 2014

Why Enums? Example in TypeScript

it's been a while since my last post, this it not because I don't have anything to write about! I have just been busy. since my last post I have created a new site called TypeScript.today this is a weekly compiled neews of whats going on in the TypeScript world, so if you have anything to share, please give me a note.


In this post I going through what an Enum is designed to solve, and then how to writing a simple Enum. I also going to show the difference between constant and computed member types.

Why Enums Sometimes as programmers we want to express the idea that a variable will be used for a specific purpose and should only be able to have a small number of values--for instance, a variable that stores the current direction of the wind might only need to store values corresponding to north, south, east, and west. One solution to this problem might be to use a number and some define'd values:

 var NORTH_WIND: number = 0;  
 var SOUTH_WIND: number = 1;  
 var EAST_WIND: number = 2;  
 var WEST_WIND: number = 3;  
 var NO_WIND: number = 4;  
 var wind_direction: number = NO_WIND;  


The problem with this approach is that it doesn't really prevent someone from assigning a nonsensical value to wind_direction; for instance, I could set wind_direction to -1 without any complaints from my compiler.
 
var NORTH_WIND: number = 0;
var SOUTH_WIND: number = 1;
var EAST_WIND: number = 2;
var WEST_WIND: number = 3;
var NO_WIND: number = 4;

var wind_direction: number = -1;


And if I looked at the type of wind_direction, i would see that it's just an integer, and this can be hard to see that something is wrong.

So the idea behind enumerated types is to create new data types that can take on only a restricted range of values. These values are all expressed as constants or computed types

Constant members declared with an integer value is assigned that value. A constant member declared without an integer value is assigned the value of the preceding constant member plus one, or the value zero if it is the first member in the enum body. The values of constant members are computed at compile-time and may be substituted for references to the members in the generated JavaScript code.
So here is an example of a enum with constant member types.
 
enum Windirections{
North = 0,
South = 1,
West = 2,
East = 3,
none = 4
}


Enums in TypeScript also support making computed members Expressions, specified for computed members must produce values of type Any, the Number primitive type, or an enum type. The values of computed members are not known at compile-time and no substitution is performed for references to computed members. heres is an example of a computed member called SoutEast where I assign it the values of South and East.

 
enum Windirections{
North = 0,
South = 1,
West = 2,
East = 3,
none = 4,
SoutEast = South + East
}
Conclusion We’ve seen how enums in the TypeScript language can be used to allow to constrain the values a variable takes on. I shown how to make constant and computed enum members. Enums can make your program more readable by eliminating magic numbers.

Friday, August 2, 2013

TypeScript : Generics, < T > is for Type

Finally we got generics in TypeScript version 0.9, I have patiently waited for that feature, and now it's here, great!

There is already a few that have ben blogging about TypeScript Generics and give some examples. This is cool, though they haven't ben telling the fundemental of generics in TypeScript. So I have trited to do that, instead of another cool example :-)

What are Generics

Generics was introduced in version 0.9. Generic types allow for code reuse with type safety. The Internal algorithm remains the same, only the type changes and disappears again on compilation and generates no artifacts to the resulting JavaScript.

Why use generics

Generics provide quality to your solution by giving your type-safe at compile-time, and reduce repetitive programming tasks, by creating generic type-safe abstractions to classes and methods.

Generic type parameters

Specifies when they instantiate a variable of the generic type.
Type parameter name commonly starts with T. Consider not just give the parameter the name T For example, call it TThing as below:
In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they instantiate a variable of the generic type.

class ItemCollection< TThing >
{
    private _things: Array< TThing >;

    Add(thing: TThing) {
        this._things.push(thing);
    }
}


Generic constrains

When you define a generic class, you can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates your class. If client code tries to instantiate your class by using a type that is not allowed by a constraint, the result is a compile-time error. These restrictions are called constraints. Constraints are specified by using the extends keyword. You can define constrains with an interface or a specific class. Example below by making a constrain to IAnimal.

class AnimalCollection< TAnimal extends IAnimal >
{
    private itemArray: Array< TAnimal >;
   
    constructor() {
        this.itemArray = [];
    }
   
    FeedAll() {
        this.itemArray.forEach(
            (item) => item.Feed()
        );                   
    }       
}


Generic classes

Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like the Array. A simple example of a generic class could be a class as follows:

class ItemCollection< T >
{
    private itemArray: Array< T >;
   
    constructor() {
        this.itemArray = [];
    }
   
    Add(item: T) {
        this.itemArray.push(item);       
    }
   
    GetFirst(): T {
        return this.itemArray[0];
    }
}


Generic methods

A generic method is a method that is declared with type parameters, as follows:

    Add(item: T) {
        this.itemArray.push(item);       
    }

You can also specify constrains on Type parameter, the below tells you that the parameter animal should implement the interface of IAnimal as follows:

function Add< T extends IAnimal >(animal: T)
{
    //...
}

Conclusion

TypeScript generics ensure type-safety and quality, reduce repetitive programming tasks, simplify the overall programming model, and do so with elegant, readable syntax. Generics is a compile-time only concept that disappears on compilation and generates no artifacts in the resulting JavaScript.

Sunday, July 14, 2013

Simple TypeScript Unit Test Project Templates

Inspired by John V. Petersen's latest post http://codebetter.com/johnvpetersen/2013/07/05/a-simple-jquery-qunit-based-javascript-unit-test-project-template/ I thought that TypeScript needed Unit Test project templates to.

I prefer using the Jasmine test framework, but knows that Qunit is popular, so I decided to make a project template for each of them. I have published them on the visualstudiogallery.

TypeScript Qunit Test Project
TypeScript Jasmine Test Project

After installing your preferred Test Project you can find it by choosing new project and go to "other langauges => TypeScript"














The basic structure for the jasmine project looks like this:



The Quint look almost the same, the only different is that I have installed the qunit.d.ts file via nuget instead of the jasmine.d.ts.
The reason for the d.ts files is placed in this structure "Scripts/typings/jasmine/jasmine.d.ts" is that, this is the basic structure when you install TypeScript definition files from nuget.

To get it working you also needs to install the chutzpah javascript runner

When this is done, the test will show up in the VS test explorer window.


Thanks John, for the inspiration. I now don't need to copy paste my TypeScript test projects.

Tuesday, February 19, 2013

Declaration source files and google analytics

What is Declaration source files?

Declaration source files are restricted to contain declarations only. Declaration source files can be used to declare the static type information associated with existing JavaScript and expose their behavior.

I have started to implement TypeScript in my projects at work :-)

In that case I had to implement google analytics but ran into the problem, that I did not have intellisence for the that.

I googled a bit and could not find any declaration file for that, so I made my own.
I can now acces ga, _gaq, _gat and the Tracker object with intellicense in my TypeScript file, nice...

Example

describe("tester Google Analytics Code  _gaq object", () => {
    it("can create _push", () => {
        _gaq.push(['_setAccount', 'UA-XXXXXXX-YY']);
        _gaq.push(['_gat._anonymizeIp']);
        _gaq.push(['_trackPageview']);

        _gaq.push(() => {
                var tracker = _gat._getTrackerByName('UA-65432-1');
                tracker._trackPageview();
            }
        );
    });  
});

I have pushed it to https://github.com/borisyankov/DefinitelyTyped but until it is merged you can get the files here https://github.com/RonnieHegelund/DefinitelyTyped/tree/master/google.analytics



Saturday, February 16, 2013

TypeScript - The rest parameter

Rest parameter in TypeScript has nothing todo with REST (REpresentational State Transfer)

If you are familiar with C# params keyword, The rest parameter is the same. The rest parameter lets you specify a function parameter that takes an argument where the number of arguments is variable.

An example could be a function that make a Sum of a variable length of numbers:


Sum(1,2,3,4);

C# example

public int Sum(params int[] list)
{
  int sum = 0;
  foreach (int i in list)
    sum += i;
  return sum;
}
TypeScript example

public Sum(...list Number[]) : number
{
    return list.reduce( 
        (a,b) => { a + b }
    );
}
And the result when compiled to JavaScript

function sum() {
    var numbers = [];
    for (var _i = 0; _i < (arguments.length - 0); _i++) {
        numbers[_i] = arguments[_i + 0];
    }
    return numbers.reduce(function (a, b) {
        return a + b;
    });
}


Sunday, January 13, 2013

Extension methods in TypeScript

/* 18/1 2013Update Remember Extension methods are code smell, so use it only where it really make sense.
Good blog post about Extension methods why its code smell http://www.daedtech.com/why-i-dont-like-c-extension-methods   
*/

When working with strings it’s likely that you’ve had to check if the string is null or empty, and
Thats no different in TypeScript.

I thougt of making an extension method for StringIsNullOrEmpty, but could not fine any documentation on this.

I know that TypeScript interfaces are open ended, so I extended the String interface like this

    interface String {
        StringIsNullOrEmpty: () => bool;
    }


Then I just need to found out how to inplement it, and used prototype for this.

    String.prototype.StringIsNullOrEmpty = () : bool{
        return this == null || this.length == 0;
    }


This works fine, but I'm not sure this is the correct way of doing this, so if you know a better way please leave a comment.

I have encapsulated the inteface and all my prototypes into a module called StringExtensions

module StringExtensions {
    interface String {
        StringIsNullOrEmpty: () => bool;
    }

    String.prototype.StringIsNullOrEmpty = () : bool{
        return this == null || this.length == 0;
    }
}


Here is a litle jasmine test.

describe("StringExtensions methods tests", () => {

    it("Given an empty string should return true", () => {

        // Fixture setup       

        var sut = "";

        // Exercise system               

        var expected = true;

        // Verify outcome

        expect(sut.StringIsNullOrEmpty()).toEqual(expected);

        // Teardown

    });   
});

Wednesday, December 12, 2012

AutoFixture for TypeScript

Automate test fixture When doing TDD.

In .NET we have AutoFixture written by Mark Seemann.
It really helps me saving time and making my tests cleaner and faster.

For the last few month I have playing around with TypeScript, it's not perfect but really has potential.

I needed a new home project based on TypeScript, but needed and idea to what I would create.

So I have made a project on GitHub called AutoFixtureTS - http://ronniehegelund.github.com/AutoFixtureTS/

Im using Jasmine as Testing framework and has 73 tests and 73 passed :-)

Check it out, any feedback would be great!