forward declaration in typescript

Max Beikirch picture Max Beikirch · Jan 17, 2013 · Viewed 8k times · Source

I've got two classes that need to know one another's members.

In C++ I'd use a forward declaration.

What do I have to do in typescript?

Answer

lhk picture lhk · Jan 17, 2013

I'm not sure, but I think you're trying to solve a problem that doesn't exist. This is perfectly valid in typescript:

class A{
    b=new B();
    func(){
        alert(this.b.member);
    }
}
class B{
    member="hello there";
}
var a=new A();
a.func();

As you can see, you can use the class B before it is defined and access its members from within class A. The same applies to functions:

var a=()=>{
    alert("function a");
    b();
}

var b=()=>{
    alert("function b");
}

a();

This should compile fine. Please note that a can only be called after b is actually defined. This won't work:

var a=()=>{
    alert("function a");
    b();
}
a();

var b=()=>{
    alert("function b");
}

You don't need forward declarations in Typescript. Just imagine that they are automatically generated for your code.

The problem becomes more complex when you need to mix Javascript and Typescript. Since all your Typescript code is statically type-checked by the compiler, interfacing Javascript frameworks is not that simple.

All variables, functions and "classes" added to your scope need to be declared before you can use them. Let's assume that you need jQuery for your Typescript project. All the jQuery magic is done with the global variable "$" but even if you've added the jQuery script to your html site, you can't just refer to "$" in your Typescript code. This is where declaration files are used. By adding the line

/// <reference path="jquery.d.ts"/>

to the top of your Typescript file, you inform the compiler about all the jQuery code that is available. .d.ts files for the most commonly used Javascript frameworks can be found here: https://github.com/borisyankov/DefinitelyTyped

The last two lines are a nice example of the syntax of .d.ts files:

declare var jQuery: JQueryStatic;
declare var $: JQueryStatic;

Now the compiler knows that two global variables named "$" and "jQuery" are available to you. Moreover if you're using VisualStudio these declaration files will allow for fantastic intellisense support.