Getting Started with TypeScript

After installing TypeScript in Visual Studio, you can get started either experimenting with sample code and starting from scratch, or, as in my case, by migrating existing JavaScript code to TypeScript.

It definitely helps if you browse through the TypeScript Language Specification (pdf) before you start.

Most likely your JavaScript code references libraries such as jQuery, etc., which can also be used from TypeScript by a mechanism called Ambient Declarations. The pdf gives a basic example for jQuery, which I extended to match the jQuery functions my code uses:

interface JQueryStatic {
    (query: string): JQuery;
    (any): JQuery;
    ajax(data: any);

declare var $: JQueryStatic;

These two declarations define the (“ambient”) jQuery variable $ as implementing the JQueryStatic interface with the functions listed.

The JQuery interface is another ambient declaration that I extended from the sample as:

interface JQuery {
    text(content: string);

    dialog(data: JQueryDialog);
    dialog(command: string);

    children: () => JQuery;

The jQuery.dialog() function can be called with various parameter sets. $(“dialog-id”).dialog(“command”) passes a command to the specified dialog, whereas $(“dialog-id”).dialog({}) initializes a dialog.

One note on the dialog() declaration: as long as I declare JQueryDialog as interface, the code raised no compilation errors if only the first two signatures are declared. However after I changed it to a class, the line

  modal: true,
  width: "540px",

raised the error message

Supplied parameters do not match any signature of call target:
Could not apply type ‘string’ to argument 1, which is of type ‘{ modal: bool; width: string; buttons: { Ok: () => void; }; open: () => any; }’

In TypeScript, method overloading must include a method signature that matches all other signatures, so I added the dialog(any) declaration, and the code compiled again.

Please note that function overloading only works on declaration level – it has no effect on the generated JavaScript code. While multiple signatures are supported, there is only one implementation.

2 thoughts on “Getting Started with TypeScript

  1. Pingback: Automatically Compiling TypeScript in Visual Studio « devioblog

  2. Pingback: Typescript Support for JavaScript Libraries such as jQuery « devioblog

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.