Hello World in TypeScript with Classes in a Web Browser

Follow the steps below to create and compile a simple TypeScript program that, when run by opening the hosting .html in a web browser, simply displays the message “Hello, world!” in an alert dialog.

These instructions use the “tsc” TypeScript compiler supplied as a module to Node.js.

Note that this is certainly not the accepted, “correct” way to create a new TypeScript project. But I wanted a tutorial that runs in a browser, includes external class files, and doesn’t require additional tools like “WebPack”, and I couldn’t find one.

1. If you have not already done so, download and install Node.js. The latest version is available for download at this link.

2. In any convenient location, create a new directory named “HelloWorldTS”.

3. Open the newly created directory in a command prompt window.

4. In the command prompt, run the command “npm install typescript”. This will install the TypeScript module to the local directory. You may be able to install it to the global registry by inserting the switch “–global” into that command, but be aware that this scenario was not tested while writing these instructions.

5. Run the command “tsc –init”. This will create the configuration file that TypeScript needs to compile the program.

6. In the newly created directory, create a new text file named “HelloWorldTS.html”, containing the following text:

<html>
<body>

<!-- classes -->
<script type="text/javascript" src="Alerter.js"></script>

<!-- main -->
<script type="text/javascript" src="main.js"></script>

</body>
</html>

7. Create another new text file named “main.ts”, containing the following text.

function main()
{
	new Alerter().showAlert("Hello, world!");
}

main();

8. Create yet another new text file named “Alerter.ts”, containing the following text:

class Alerter
{
	showAlert(message : string)
	{
		alert(message);
	}
}

9. Run the command “tsc” and verify that no error messages were generated.

10. Open HelloWorldTSC.html file in a web browser that runs JavaScript and verify that a message dialog is displayed that says “Hello, world!”.

Advertisement
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

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

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 )

Connecting to %s