Prefix - typeof and typename operators

Monday, September 26th, 2011     #javascript #everything

Prefix does not (and will not) have an equivalent to .NET's runtime reflection capabilities. It does however have something a little better than what JavaScript provides - introducing the typename and typeof operators...

This post is about Prefix - a modern language that compiles to JavaScript. A language where C# is the inspiration - not the goal. Read more on the Prefix Project Page.

I've always thought JavaScript's runtime type support to be rather lame - not so much in what it can provide, but simply that it's rather inconsistent. For example, using typeof on any custom class/object simply yields "object". Great - not.

In Prefix I wanted to improve this situation a little and provide something a little more reliable. Prefix has two type inspection operators:

typeof
returns the constructor of an object or value
typename
returns a descriptive name for an object type

Both operators can accept either an object instance, or a compile type type name.

For the built in types (boolean, string etc...), typeof returns the boxed object constructor (eg: String.constructor) while typename returns the equivalent of the JavaScript typeof operator (eg: "string", "boolean", "number" etc....)

For Prefix classes, including generic classes typeof returns the class function and typename returns a descriptive name of the class - with generic arguments substituted. eg:

{{C#}}
extern dynamic Console;

class Bar
{
}

class MyClass<T>
{
    public void fn()
    {
        Console.WriteLine(typename(T));
    }
}

new MyClass<bool>().fn();
new MyClass<int>().fn();
new MyClass<Bar>().fn();
new MyClass<MyClass<int>>().fn();
Console.WriteLine(typename(MyClass<int>));
boolean
number
Bar
MyClass<>[number]
MyClass<>[number]

Note that although Prefix distinguished between int and double at compile time, there is no such distinction at runtime - hence the appearance number in the resulting typename.

There are a couple of runtime helper functions to support these operators but as always they're tiny, automatically generated by the compiler and only generated when actually needed.

(Don't forget Prefix also supports runtime type querying via the is and as keywords).

« Older - Prefix - Anonymous Functions and Lambdas Newer - Porting 'Burst Fish' to Prefix »