TypeScript - Write Your First Program In HTML and TS

First of all, we need to install node.js for running TypeScript code

  • Visit  Node.js official website, Download and Install Node.js 
  • After Node.js installation, use NPM package manager to install TypeScript on your system 
npm install typescript 
  • Run command tsc on command prompt to verify the TypeScript installation.
  • Download and Install VS code IDE. Install some useful VS code plugins.
    • ESLint
    • Live Server
    • Prettier - Code formatter
  • Open project folder in VS code 
  • Create two files (One .html and One .ts file) , We use .ts extension for TypeScript file.
    • index.html
    • script.ts 
  • In script.ts file write following code.
    function sayHelloWorld(): void {
      console.log("\n");
      console.log("*** Hello World from Type Script code. ***");
      console.log("\n");
    }
    
    sayHelloWorld();
  • Open VS code terminal run "tsc  script.ts" command, you will see a new script.js file in your folder. The generated file is equivalent javascript file generated by TypeScript transpiler. 
    • tsc script.ts 
    • We can also user tsc script.ts --watch command, now if any change happens in .ts file it will automatically re-run the Transpiler and changes will reflect on .js file
  • Now you may use Node server to run the script.js file, also we can use script.js file in HTML page.

  • For running script.js file in node user command "node script.js"

  • For using script file in index.html file, use <script> tag to use script file, same as what we do for javascript file.

    ?<html>
        <head>
            <title>TS - Basic Concepts</title>
            <script src="script.js"></script> 
        </head>
        <body>
            Hello World <br><br>        
        </body>
    </html>
    Please note here we will use script.js in src, not script.ts
     
  • Now time to see HTML file result. Right click on index.html file and click on Open with live server. 



    Right click on web page and open console tab. You will see the text there.

Awesome, Your TypeScript playground is ready now. Next you may setup "tsconfig.json" for complier options. Read more here

See source code in GitHub

Next Recommended Reading Get Set in TypeScript