Class type check with TypeScript

Class type check with TypeScript

I’m very excited about TypeScript, so I started to play with it. As an Actionscript developer, it makes Javascript less hard.
However, in Actionscript it is possible to check the type at run-time using the is operator:
var mySprite:Sprite = new Sprite();
trace(mySprite is Sprite); // true
trace(mySprite is DisplayObject);// true
trace(mySprite is IEventDispatcher); // true

Is it possible to detect if a variable (extends or) is a certain class or interface with TypeScript? I couldn’t find anything about it in the language specs, it should be there when working with classes/interfaces.

Solutions/Answers:

Solution 1:

4.19.4 The instanceof operator

The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, and the right operand to be of type Any or a subtype of the ‘Function’ interface type. The result is always of the Boolean primitive type.

So you could use

mySprite instanceof Sprite;

Note that this operator is also in ActionScript but it shouldn’t be used there anymore:

Related:  Javascript: Extend a Function

The is operator, which is new for ActionScript 3.0, allows you to test whether a variable or expression is a member of a given data type. In previous versions of ActionScript, the instanceof operator provided this functionality, but in ActionScript 3.0 the instanceof operator should not be used to test for data type membership. The is operator should be used instead of the instanceof operator for manual type checking, because the expression x instanceof y merely checks the prototype chain of x for the existence of y (and in ActionScript 3.0, the prototype chain does not provide a complete picture of the inheritance hierarchy).

TypeScript’s instanceof shares the same problems. As it is a language which is still in its development I recommend you to state a proposal of such facility.

See also:

Solution 2:

TypeScript have a way of validating the type of a variable in runtime.
You can add a validating function that returns a type predicate.
So you can call this function inside an if statement, and be sure that all the code inside that block is safe to use as the type you think it is.

Related:  How do I run a Node.js script from within another Node.js script

Example from the TypeScript docs:

function isFish(pet: Fish | Bird): pet is Fish {
   return (<Fish>pet).swim !== undefined;
}

// Both calls to 'swim' and 'fly' are now okay.
if (isFish(pet)) {
  pet.swim();
}
else {
  pet.fly();
}

See more at:
https://www.typescriptlang.org/docs/handbook/advanced-types.html