By 06/07/2015 19 Comments

TypeScript Explicit Casting

Explicit Casting:

  • In TypeScript we can explicitly specify the types of the objects & that process is called Explicit Casting.
  • An object of one type can be cast to another type by using < > syntax.
  • TypeScript allows us to explicitly cast from any type object to a data type “any” and vice versa.
  • TypeScript compiler performs casting at compile-time and it does not generate casting in JavaScript code at run-time.

Example:

class DemoA { // A class declaration.

// Implicitly null parametrized void type functions are declared.
    show1() {
        document.write("showA() function in class A");
    }
    show2() {
        document.write("after implicit/explicit casting this function cannot be called!");
    }
}
class DemoB { // Another class declaration.
    showB() {
    }
}

// An object creation of DemoA class type.
var objA: DemoA = new DemoA();

/* A function of class DemoA is being called through an object reference. NOTE: this function is being called before implicitly/explicitly cast occurs. */
objA.show1();

/* An object creation of DemoB class type. NOTE: this object is being created as “any” type. */
var objB : any = new DemoB;

/* An implicit cast from 'any' DemoB object type to 'DemoA' object type. */
objA = objB; 

// OR

/* An explicit cast from 'any' DemoB object type to 'DemoA' object type. NOTE: here a < > syntax is being used which indicates an explicit casting. */
objA = <DemoA> objB;  

/* Another function of class DemoA is being trying to called through an object reference. NOTE: this function is being called after implicitly/explicitly cast has occurred. This function will not be called/invoked. */
objA.show2();





Next Tutorial →


← Previous Tutorial


Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .