TypeScript is a super set of JavaScript. Any piece of JavaScript is also a valid code in TypeScript. TypeScript is all about making JavaScript scale. It is about making easier to build medium to large applications in JavaScript. It gives the ability to write code in manageable and a more object oriented way and the flexibility to run in any browser like any other JavaScript code. TypeScript code is compiled back in to plain old JavaScript which is exactly what we are going to do in this tutorial. TypeScript compiler is also written in TypeScript language.
First we need to install Node.js.
Download it from here. After the default install PATH will be set automatically.
Open the CMD window in Windows by pressing Window button + R and type cmd then enter. On CMD window paste the following
npm install -g typescript
It will install TypeScript in your PC. Type
tsc
to see different options made available by it.
Now for our Hello World tutorial we need to create a text file, say hello.ts and in it, type the following
class Hello {
constructor (public msg: string){
}
sayHello() {
return "<h2>" + this.msg + "</h2>";
}
};
var hello = new Hello("Hello World, What do you think of TypeScript? ");
document.body.innerHTML = hello.sayHello();
save the file hello.ts and compile the file using the command
tsc hello.ts
This will produce a file
hello.js
in the same directory. Now create a new file named hello.html in the same directory. This html file is responsible for executing the compiled JavaScript file. Put the following code in hello.html
<!DOCTYPE html>
<html>
<head><title>TypeScript Hello World | Tutorial Jini </title></head>
<body>
<script src='hello.js'></script>
</body>
</html>
save the file and on cmd line type this
start hello.html
This will open a browser with our js executed inside it.