Class Scope

Topics: Language Specification
Nov 20, 2012 at 9:57 AM

module Sample {
    "use strict"

    class Bar extends Foo {
        name: string = "hello, world!";
    }
    
    class Foo {
    }

    window.onload = () =>
    {
        var p = new Bar();
        alert(p.name);
    }
}

The above sample gives "Uncaught TypeError: Cannot read property 'prototype' of undefined" error.

The error is related with scoping.

If i define Foo before bar, it works well.

As i understood typescript mimics javascript scopes as it.

Is it possible to order classes base on their usage?

If its difficult is it possible that typescript visual studio plugin gives warning or errors about such similar situations?

Thanks

 

Coordinator
Nov 20, 2012 at 4:31 PM

If you think of classes as just syntactic sugar for creating constructor functions, you'll have the right model to think about them in TypeScript.  We're not trying to reorder code but instead to follow a very simple translation to JavaScript.  This helps us keep the output JavaScript as similar to the input as possible.

Coming from other languages, the ordering might be confusing (and we could definitely have better linting/compiler warnings to help catch errors like this sooner), but in some ways it's not too far different from declaring a variable before you use it.

Nov 21, 2012 at 2:52 PM
Edited Nov 21, 2012 at 2:54 PM

You could try splitting it up into multiple files:

Foo.ts:

module Sample {
    "use strict"

    class Foo {

        public name: string;

        constructor () {

            this.name = "Foo";
        }
    }
}



Bar.ts:

/// <reference path="Foo.ts" />

module Sample {
    "use strict"

    class Bar extends Foo {

        constructor () {
            
            super();

            this.name = this.name + "bar!";
        }
    }
}
Nov 22, 2012 at 11:15 AM

Thanks for alternative,

i will go with your suggestion.