TypeScript Casting Gotchas

Below are two TypeScript “gotchas” that I have come across while writing my first TypeScript app.

1) Here we are creating an instance of the customer class and calling a method to write some data to the console.
Then the object is turned into JSON and then parsed and cast as a customer class. There is no TypeScript compile time error, but there is a runtime error:

class Customer {
    constructor(public name: string) {
    showInfo() {
        console.log('time:' + new Date().getMilliseconds() + ' name:' + this.name);

window.onload = () => {
    var customer = new Customer('russ');

    var customerJSON = JSON.stringify(customer);
    var customerCasted = <Customer>JSON.parse(customerJSON);
    customerCasted.showInfo();//RUNTIME ERROR


Visual Studio will let us compile and run this code without an error so why isn’t there a showInfo method on our parsed Customer class?
Because TypeScript is still just JavaScript.  There is no magic at runtime, the castedCustomer object is an anonymous object with no specific object definition.

Once this is realized you can then change the code and instantiate a new customer which will of course then be of type Customer and have the correct showInfo method.

window.onload = () => {
    var customer = new Customer('russ');

    var customerJSON = JSON.stringify(customer);
    var customerCasted = <Customer>JSON.parse(customerJSON);
    //customerCasted.showInfo();//RUNTIME ERROR

    var fixedCustomer = new Customer(customerCasted.name);

2) Another one is casting an object to another type which it is not related by interface or inheritance.

class Dog {
    constructor(public name: string, public nickName: string) {
class Cat {
    constructor(public name: string) {
class Dinosaur {
    constructor(public dinoName: string) {

window.onload = () => {
    var dog = new Dog('spot', 'doggy');
    var cat = new Cat('furball');
    var dino = new Dinosaur('rex');

    var dogB = <Dog>cat;//OK
    var dogC = <Dog>dino;//COMPILE ERROR

    var catB = <Cat>dog;//OK
    var catC = <Cat>dino;//COMPILE ERROR

    var dinoB = <Dinosaur>cat;//COMPILE ERROR
    var dinoC = <Dinosaur>dog;//COMPILE ERROR


The Dog class and Cat class share part of the same typed definition(name: string). Because of this they are convertible as far as TypeScript is concerned instead of producing a compile time error. Although the Dinosaur class only has one string property it cannot be casted to or from because the property-name is different.

Viewing JSON in Internet Explorer

(Originally Posted on November 21, 2013)

Recently I have been working on some Web API controllers and found it bothersome to use Internet Explorer to view raw JSON results.  Instead of just seeing the JSON text you get a popup from IE asking how you would like to open up the JSON file.

The “fix” for this is to save the lines below in a text file with the extension “.reg” to modify the registry.

Windows Registry Editor Version 5.00;
; Tell IE 7,8,9,10,11 to open JSON documents in the browser on Windows XP and later.
; 25336920-03F9-11cf-8FD0-00AA00686F13 is the CLSID for the "Browse in place" .
[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json]

This is telling IE that for the “application/json” MIME type that it can be viewed “in place” or just directly in the browser. There are a few resources I found with differing information but I found this specific registry fix on Code Project.

MongoDb data access with .NET

Not the usual choice for .NET development but NoSql document databases are becoming more common in the development world.

Getting MongoDb running on Windows

  1. To get started with MongoDb first download the correct version for your operating system.
  2. Create the following new path c:\data\db
  3. From the extracted files, run MongoD.exe.
  4. That’s it.

.NET with MongoDb

To communicate with MongoDb you need to first download the assembles from github or do it the smart way and use Nuget.  With this C# driver you can now query the database directly using LINQ statements:

There are a few different ways you can construct  the data model when using C# with MongoDb such as using a BsonDocument from a JSON string or do it the “typed” way and use custom objects for your documents.

Note the BsonId Attribute, which is  needed to act as the document identifier.

public class Customer
    public ObjectId CustomerId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime CreatedDate { get; set; }
    public IEnumerable Orders { get; set; }

Data Access

With MongoDb you do not need to specifically create a new database or collection. When calling the save method, if the database is not there, it will be created, if that collection is not there, it will be created.


    string mongoConn = "mongodb://localhost/?safe=true";
    var server = MongoServer.Create(mongoConn);
    var myStore = server.GetDatabase("myStore");
    var coll = myStore.GetCollection("myCustomer");

    var cust = new MongoCustomer()
        FirstName = "john",
        LastName = "doe",
        CreatedDate = DateTime.Now,
        MongoOrders = GetSomeOrders()

(You can also use the Insert or InsertBatch methods in the MongoCollection Object.


    string mongoConn = "mongodb://localhost/?safe=true";
    var server = MongoServer.Create(mongoConn);
    var myStore = server.GetDatabase("myStore");
    var coll = myStore.GetCollection("myCustomer");

    var q = from c in coll.AsQueryable()
            where c.FirstName.Contains("russ")
            select c;

Performance Testing

Our simple data model includes a one to many relationship of a Customers to Orders.

MongoDb vs SQL Server 2008 Express



As you can see, inserting data is faster in MongoDb, especially when the data model gets more complex.


The loaded data for selection testing includes 3,000,000 customers and 10 orders per customer in both sql server and MongoDb.

With a large amount of data being returned MongoDb is much faster, but it seems the RDBMS had the advantage for smaller queries, at least with this data setup.

If the data structure and business need fall in line with the document database model then using MongoDb with .NET can make some very high performing applications.

Visual Studio 2012 JavaScript Updates

Visual Studio 2012 RC is out and it brings quit a few changes, especially for developing JavaScript.

JavaScript Object Definition

Visual Studio 2012 finally adds in the ability of going to an object’s definition just like when coding in C#.  You can do this by either by right clicking the object or by pressing F12.


External JavaScript Intellisense Support

With previous versions of Visual Studio in order to get Intellisense to work with external JavaScript files  you had to add a reference path to a vsdoc file (which usually wouldn’t work without rebuilding Intellisense using ctrl + shift + J):

///<reference path="jquery-1.6.4-vsdoc.js" />

In Visual Studio 2012 after the script is added, Intellisense will work with nothing extra needed:


JavaScript Function Documentation

Documentation is something that is usually missing from JavaScript source files. There is now built in support for signatures within JavaScript functions. There can also be multiple signatures for overloading.

Calling Function With Documentation Comments:

    function getTax(rate, amount) {
        ///<summary>Get Calculated Tax</summary>
        ///<param name="rate" type="number">Tax Rate</param>
        ///<param name="amount" type="number">Money Amount</param>
        return rate * amount;


It seems Visual Studio is now treating Javascript like an actual supported language.