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.

6 comments:

  1. Thanks for writing such a good article, I stumbled onto your blog and read a few post. I like your style of writing... SEO services

    ReplyDelete
  2. It is nice blog Thank you porovide important information and i am searching for same information to save my time AngularJS4 Online Course Banglaore

    ReplyDelete
  3. This is a nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
    python Training in Pune
    python Training in Chennai
    python Training in Bangalore

    ReplyDelete
  4. I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.
    Best Devops Training in pune
    Devops Training in Bangalore
    Power bi training in Chennai

    ReplyDelete
  5. Excellent blog!!! I got to know more useful information by reading your blog. Thanks for posting this blog.

    Apache Spark and Scala Online Training
    Spark and Scala Training

    ReplyDelete