Wednesday, October 10, 2018

TypeScript - First Project - Hello World

In my project folder i have two files:

$ ls -l 
total 8
-rw-r--r-- 1 ubuntu ubuntu 223 Oct 10 10:23 index.html
-rw-r--r-- 1 ubuntu ubuntu 390 Oct 10 10:17 script.ts

This first file: index.html

Its contents are as follows:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE-edge">
<title> My TypeScript Project 01 </title>

</head>

<body>

    <script src="./script.js"></script>
</body>
</html>

The second file is : script.ts. Notice that the extention to this file is .ts. It means, that it is a TypeScript file and not a JavaScript file. For the content of this typescript file. let us visit the online playground of TypeScript: http://www.typescriptlang.org/play/

We will notice that there is already a program in the TypeScript section of the window on the left pane. We will copy the content and paste it in our script.ts file:

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        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);

Note that this is a TypeScript file and not a JavaScript file. Let us save the file script.ts. Now, we will compile it using the TypeScript transpiler.
$ tsc script.ts 
$ ls -l
total 12
-rw-r--r-- 1 ubuntu ubuntu 223 Oct 10 10:23 index.html
-rw-r--r-- 1 ubuntu ubuntu 447 Oct 10 20:27 script.js
-rw-r--r-- 1 ubuntu ubuntu 390 Oct 10 10:17 script.ts

We can see that we have a new file: script.js.

Now, let us open the page index.html in a browser. We can see the following output:



Reference: 




No comments:

Post a Comment