This project is read-only.

type/class introspection at running time

Topics: General, Language Specification
Nov 29, 2013 at 5:33 PM
I hope this hasn't already been suggested or even worse already available!

One feature that would enhance TypeScript would be the possibility to query the type/class of an object at running time. The actual typeof operator from JavaScript returns 'function' for any kind of object that use a TypeScript class (logic!). An operator close to "typeid in C++", which return either an unique string containing the name of the class or a hash, would be welcomed.
Technically I guess that a field "type" on a javascript object would be enough to carry this information. To avoid any overhead with this feature could be disable/enable with either a keyword on the class or a flag at compilation.

I imagine various usages with this feature:
  • Type's specialization / generics' specialization.
  • Advanced reflection
  • ...
Dec 1, 2013 at 6:26 PM
There is a related discussion on the forum.

One of the ideas mentioned was to have something like the following:
var typeName      = getType(foo.A).getName();
var numericFields = getType(foo.A)
                    .filter(f=> f.getType() == numeric)
                    .map(f=> f.getName());
There was also a recent post by @jonturner related to mixins that I found interesting.

Combining that suggestion we could define an extension method as follows:
interface Type {
  getName(): string;
  getFields(): Type[];

var type : Type     = @Type(foo.A);
var typeName      = type.getName();
Which compiles into:
var type     =  new Type("foo.A", /*other meta*/);
Basically, TypeScript assumes the existence of a user-defined class called Type
   class Type {
        constructor(typeName: string, fields: Type[]){}