Typescript Hello world in local system Example

Step 1: Install Typescript in Your Local Machine

Install typescript in your local machine to compile and test typescript. Instructions / steps to install typescript can be found in the below link

We need typescript in local,because typescript is not like javascript which can directly run on the browser. It has to be converted to javascript before running in any browser.

This is because all browsers are currently supporting ES5 only and typescript is ES6, so typescript compiler converts typescript (ES6) file to javascript (ES5) file internally to make it runnable in the browsers.

So we need typescript to be installed on our local machine to compile and convert the typescript to javascript before running it on browsers.

How to install typescript in windows 10?

 

Step 2: Create your test project

 

Once the installation completed, create a folder named “my-typescript” and have one html and one ts (typescript file) inside it.

Note: ./hello.js only imported in the html file, not .ts file, because .ts should be compiled and converted to .js file before running.

 

hello.html:

<!DOCTYPE html>

<html lang="en"> 

<head> 

  <!-- Required meta tags --> 

  <meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1,shrink-to-fit=no"> </head>

<body>

<script src="./hello.js" ></script>

</body>

</html>

 

 

hello.ts:

 

function Greeter(greeting: string) {
this.greeting = greeting;
}

Greeter.prototype.greet = function() {
return "Hello, " + this.greeting;
}

let greeter = new Greeter("world");

let button = document.createElement('button');
button.textContent = "Say Hello";
button.onclick = function() {
alert(greeter.greet());
};

document.body.appendChild(button);

 

 

Folder structure before compiling the typescript file,

Typescript Hello world in local system Example

 

Step 3: Compile the typescript code now

 

Typescript Hello world in local system Example

 

Now the folder has .js file additionally because the command tsc compiles the typescript and creates .js file,

 

Typescript Hello world in local system Example

 

 

Now open and see the output:

 

Typescript Hello world in local system Example

 

 

Typescript Hello world in local system Example

 

This example has been taken from typescriptlang.org playground (typescript official site)

Leave a Reply