Execute Typescript

Want to easily execute Typescript?

Cool thing is that TSC.exe (that comes with the Typescript installation) has a -e option to execute a file. So you can simply write:

tsc -e somefile.ts

That command will compile the .ts to .js and execute that js.

But we also like to be able to see some generated output. We can do that using the IO object that TSC creates for us. So let’s write a small ts file:

declare var IO;
IO.print("hello world");

Execute that one and you get “foo” in the console. Add the TSC -e command as an external tool to your Visual Studio and you have a useful shortcut to execute whatever ts you like.

A few useful functions within IO:

IO.writeFile(path: string, contents: string): void;
IO.fileExists(path: string): bool;

Full IO.d.ts in this gist. (It’s auto-generated from the TypeScript source.) However – to use the d.ts (instead of the anonymous declare var IO;) you need to use a rather strange workaround currently (I expect it to be fixed soon?):

Workaround to use io.d.ts in current version of Typescript

Create an empty file to reference to (for example empty.ts). And add refs to that file aswell as to io.d.ts:

/// <reference path="empty.ts"/>
/// <reference path="io.d.ts"/>
IO.print("hello world");

Then execute it with the –out parameter:

tsc -e somefile.ts --out somefile.js

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s