☰ See All Chapters |
Typescript Example
In this tutorial you will learn to execute simple TypeScript code. First you create TypeScript file then transpile (compile) this TypeScript to JavaScript. Now this JavaScript is the executed in browser. Before proceeding to execute this example you should have TypeScript execution environment to convert TypeScript to JavaScript. Please refer our previous tutorial Typescript Environment Setup and make sure you have ready environment.
Below steps guide you to run sample TypeScript Code.
Step 1: Create welcome.html
<!DOCTYPE html> <html> <body> <script src="welcome.js"></script> </body> </html> |
Step 2: Create typescript file
Create welcome.ts in the same directory where welcome.html is created
function welcome(person) { return "Hello, " + person; }
var user = "Manu Manjunatha";
document.body.innerHTML = welcome(user); |
We used “.ts” extension, but this code is just JavaScript. This is just a sample app. You could have copy/pasted this straight out of an existing JavaScript app.
Step 3: Compiling typescript file
Launch command prompt and navigate to the directory containing welcome.ts (or directly open command prompt for the directory containing welcome.ts)
At the command line, run the TypeScript compiler: tsc greeter.ts
tsc should produce no output. In many command line traditions, no output is actually a mark of success.
The result will be a file welcome.js which contains the same JavaScript that we fed in.
If you create multiple files, we can compile multiple files at once by listing all of them or by applying wildcards:
tsc main.ts profile.ts
Or we can compile all file in one folder at once
tsc *.ts
Step 4: Launch welcome.html
Open welcome.html file from any browser and check the ouput.
All Chapters