Please add support for identifying classes of objects via 'is'.

Topics: Language Specification
Oct 3, 2012 at 7:49 PM

JavaScript only offers reflection via typeof() operator, which only returns "object" for instantiated Objects, and can therefore not be used for identifying Objects in regards to their classes and inheritance:

class Animal {...}
class Snake extends Animal {...}
class Horse extends Animal {...}
// returns 'object'
typeof( new Snake() );
// also returns 'object'
typeof( new Horse() );

// evaluates incorrectly to 'true':
var b : bool = typeof( new Snake() ) == typeof( new Horse() );

In order to allow reflection at the simple level of "is this object of that type?" I am proposing support for an 'is' operator:

// evaluates to 'false':
var b : bool = (new Snake()) is (new Horse());

// also true (see my other proposal about support for 'Class'):
var b2 : bool = (new Snake()) is Snake;

// also true, because Snake is derived from Animal:
var b3 : bool = (new Snake()) is Animal;

'is' would also make it safer to use 'as' (see my proposal about adding support for explicit casts), i.e.:

var a : Animal = new Snake();
if( a is Snake )
{
  var s : Snake = a as Snake;
}

Thanks!

Oct 3, 2012 at 8:00 PM

JavaScript has the instanceof operator which may work for what you want:

var b = (new Snake()) instanceof Horse; // false
Oct 3, 2012 at 8:12 PM
Edited Oct 3, 2012 at 8:13 PM

'instanceof' doesn't seem to work for classes that implement interfaces:

 

interface IAnimal { ... }
class Animal implements IAnimal {...}
class Snake extends Animal {...}
class Horse extends Animal {...}

var sam = new Snake();
// works:
if( sam instanceof Animal )
	alert( "Sam is an Animal" );

// flags an error for 'IAnimal' :
if( sam instanceof IAnimal )
	alert( "Sam is an Animal" );

 

If this is considered a bug then yes, 'instanceof' would work for me!

Thanks,

- Bernd

Oct 3, 2012 at 8:22 PM

Not a bug. Interfaces are purely type information, and TypeScript's type information is only present at compile time. Instanceof is a runtime feature of JavaScript so has no idea what TypeScript types originally existed.

Identifying the lineage of objects in TypeScript must be done the same way it is done in JavaScript today, such as by setting sentinel values during construction or by examining the structure of the object (eg. if it has a 'talk' property it must be an animal). TypeScript could possibly provide a library method to do this for you, but it's a difficult thing to do right since the type information is not available at all at runtime.

Oct 3, 2012 at 8:27 PM

Thanks for clarifying!

Let me rephrase my request:

I am asking for an 'is' operator that is a superset of JavaScript's 'instanceof' operator plus support for identifying implemented interfaces.

Thanks!

- Bernd