Exercise 11.8

This is Exercise 11.8, lecture on Typescript and other Javascript extensions, used in the course IDATA2301 Web technologies at NTNU, campus Aalesund.

Go back to exercise list.

Purpose

The purpose of the exercise is to get your first experience with TypeScript. Note: be ready to use a bit of time. If you have never used Typescript before, there will be a bit of setup. the browser can't run Typescript directly, therefore you need to install a transpiler.

Instructions

  1. Install Node.js on your computer. Node is a headless Javascript engine: it can run on the computer/server, outside the browser.
  2. Install Typescript transpiler using the following command in the terminal npm install --global typescript
  3. Create a new project directory.
  4. Inside the folder create a Typescript configuration file tsconfig.js
  5. Create file hello.ts and inside it create a TypeScript code:
  6.         const greet = (person: string) => {
              console.log('TypeScript sends a greeting to ' + person);
            };
            greet('Chuck');
  7. To compile this file to Javascript, open terminal (in your IDE) and run the following command inside the project directory: tsc hello.ts
  8. Note: if you are on Windows 10 and get the error tsc.ps1 cannot be loaded because running scripts is disabled on this system, you can fix it as described here: Run a new PowerShell instance as the administrator and execute the following command: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned . Press Y when asked.
  9. If everything went well, now you have a Javascript file hello.js inside your project directory.
  10. Open the file in the IDE and look at the content. Plain Javascript, right?
  11. Create an HTML file and include the hello.js Javascript there.
  12. Open the HTML file in the browser and look into the Developer console. Do you see it printing the greeting?

Solution

You can find a solution here.