Typescript hello world program for beginners

Do you want to learn Typescript? If yes, then start with the typescript hello world program for beginners. Before this, we will also learn how to set up a development environment for Typescript.

As a developer we know, Typescript is a front-end language that is rapidly gaining acceptance in the developer community. Typescript overcomes several of JavaScript’s shortcomings while retaining all of its advantages.

So, many business seekers take developers who can work in both JavaScript and TypeScript.

Here we will explore the below topics:

  • What is typescript?
  • Why do we use typescript?
  • Advantages of using typescript
  • How to use typescript?
  • Difference between typescript and javascript
  • Setup the Typescript development environment
  • First Hello World with Typescript

What is Typescript?

  • As we know, Typescript is a javascript superset
  • On top of JavaScript, TypeScript is built. You begin by writing the TypeScript code. The TypeScript code is then compiled into normal JavaScript code using a TypeScript compiler.
  • You may deploy the basic JavaScript code to any environment that supports JavaScript. TypeScript files have the.ts extension, whereas JavaScript files have the.js extension.
  • A TypeScript program is one that has no syntax mistakes in its JavaScript code. This means that all JavaScript programs are TypeScript programs. This is really useful if you are transitioning an existing JavaScript codebase to TypeScript.

Read Typescript Identifiers and Keywords

Why do we use typescript?

Here we will see why we need to use typescript.

TypeScript is used for two major reasons:

  1. TypeScript adds a type system to JavaScript to help you avoid several difficulties with dynamic types.
  2. TypeScript incorporates future JavaScript capabilities, such as ES Next, so that you may use them now.

For example Dynamic types in JS, and we will see how typescript is better than javascript

The data variable’s type varies depending on the value provided to it.

The typeof operator is used at runtime to determine the type of the data variable:

let data;
data= "Good morning";
console.log(typeof(data)); // string

data= 1000;
console.log(typeof(data)); //number

console.log(typeof(data));// undefined

As you can see, the variable’s type changes as soon as a value is assigned.

Additionally, JavaScript doesn’t need to be explicitly told the type. The type will be automatically determined by JavaScript from the value.

Flexible dynamic types are available. They do, however, also cause issues.

Issues with dynamic types

Let’s say you have a function that, given an id, produces an employee object:

function getEmployee(id){ 
return 
{ 
id: id, 
name: ` ${id} Alex`, 
department: 'IT'
 } }

The following retrieves the employee with ID 1 and displays its details using the getEmployee() function:

const employee= getEmployee(1);
console.log(`The employee ${employee.Name} department $${employee.department}`);

So the output is:

The employee undefined, department IT

This output we didn’t expect. This code has a problem because the employee object lacks a Name attribute. It has the lowercase letter n in the name property.

But you won’t know until you execute the script.

When using JavaScript, it’s normal to reference a property that doesn’t exist on the object.

const showEmployee = (name, price)  => {
  console.log(`The employee ${name} department ${department}$.`);
};

const employee= getEmployee(1);
showEmployee (employee.department, employee.name);

The output will be:

The employee IT department $ 1 Alex

This time, the showEmployee () method receives the inputs out of order. This is another issue that frequently arises while using JavaScript.

Also read, Data types in typescript with examples

How typescript, solves this issue

To fix the issue of referencing a property on an object that isn’t there, you do the following:

First, use an interface to specify the employee object’s “shape.”

interface Employee{
    id: number,
    name: string,
    department: string
};

Second, define the employee type directly as they getEmployee() function’s return type.

function getEmployee(id) : Employee{
  return {
    id: id,
    name: ` ${id} Alex`,
    department: 'IT'
  }
}

The code editor will notify you right away if you make a reference to a property that doesn’t exist:

const employee = getEmployee(1);
console.log(`The employee ${employee.Name} department $${employee.department}`);

You can see the error in the Name property, so when you hover over the property, you can see the below error: Property ‘Name’ does not exist on type ‘Employee’. Did you mean ‘name’?

typescript hello world program
Typescript introduction

We specifically assign types to function parameters in order to address the issue of providing the arguments in the wrong order:

const showEmployee = (name: string, department:number)  => {
    console.log(`The employee ${name} department ${department}$.`);
  };

And the showEmployee () method will return an error if you send it the incorrect kind of argument: Argument of type ‘string’ is not assignable to parameter of type ‘number’.

typescript hello world vscode
why typescript is better than javascript

Here we see JavaScript utilizes dynamic typing. Although it provides flexibility, it also causes a lot of issues. To address these issues, TypeScript extends JavaScript with an optional type system.

Read TypeScript Enum

How to use TypeScripts?

A typescript code is written in a file and saved with .ts extension and then compiled into JavaScript using the Typescript compiler. The Typescript compiler can be installed on any Operating System such as Windows, Mac OS, and Linux.

It can be written in any code editor like visual studio and visual studio code or Notepad++. The command tsc <filename>.ts compiles your Typescript code into a plain JavaScript file.

Advantages of TypeScript

  • TypeScript is purely object-oriented programming.
  • Typescript can be used for client-side and server-side development alike.
  • The ability to compile down to a version of JavaScript that runs on all browsers.
  • One of TypeScript’s most significant features is its code completion and IntelliSense. As the code is written, Intellisense offers active hints.
  • ECMAScript 6 Feature Support Static Type-checking, TypeScript compiler will check the type (to surface more typing errors at compiling time). This is not available in JavaScript.

Difference between TypeScript and JavaScript

  • TypeScript is known as an Object-oriented programming language whereas JavaScript is a scripting language.
  • TypeScript has a feature known as Static type-checking but JavaScript does not have this feature.
  • TypeScript gives support for modules whereas JavaScript does not support modules.
  • TypeScript has Interface but JavaScript does not have Interface.
  • TypeScript support optional parameter function but JavaScript does not support optional parameter function.

Read TypeScript Set and Weakset

Setup Typescript development environment

Here we will see how to setup the typescript development environment.

To set up the typescript development environment, we need the below prerequisites:

  1. Install node js

To install the node js, click on the link, based on your operating system, and choose the Long term support option.

2. Install Typescript compiler

Launch the Terminal on Mac, Linux, or Windows, and then run the following command to install the TypeScript compiler:

npm install -g typescript

To verify the TypeScript compiler’s current version after installation, enter the following command:

tsc  --v

It will return like the below screenshot:

Setup the Typescript development environment
Setup the Typescript development environment

Run the following command from the Command Prompt on Windows or the Terminal on macOS or Linux to install the ts-node module globally:

npm install -g ts-node

3. Install Code Editor

So I will use the vs code editor, which you can download from this link, based on the operating system

Read TypeScript Map

First Hello World Program with Typescript

Here we will create our First Hello World with Typescript.

So here we will see:

  • Node.js’s TypeScript Hello World program
  • Web browsers’ TypeScript Hello World program

Node.js’s TypeScript Hello World program

  • To create the first hello world program, create a new folder, e.g. TypescriptExample.
  • Then open the vs code or any code editor.
  • Then create a new file inside the folder, named app.ts file, .ts extension is used for typescript.
  • Now write the below code in the app.ts file:
let greetings: string = 'Hello World!';
console.log(greetings);

Next, open the new terminal in vs code, and write the below command, to compile the app.ts file

tsc app.ts

If the above command runs successfully, then the typescript compiler will generate an app.js file.

Then run the app.js file in node.js, you can use the below command:

node app.js

You can see the output as Hello World!.

If you set up a TypeScript development environment and installed the ts-node module, you can compile a TypeScript file and run the result file with only one command:

ts-node app.ts
Setup the  development environment for Typescript
Setup the development environment for Typescript

Web browsers’ TypeScript Hello World program

Now change the code of app.ts file, with the below code:

let greetings: string = 'Hello World!';
// create a new heading 1 element
let heading = document.createElement('h1');
heading.textContent = greetings;
// add the heading the document
document.body.appendChild(heading);

Then create an index.html file, and write the below code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TypeScript: Hello World!</title>
</head>
<body>
    <script src="app.js"></script>
</body>
</html>

Then write the below command to compile the app.ts file.

tsc app.ts

Next, run the code manually, or you can install the live server in your vs code, which will show the live changes in your code. You can see the Hello World on the browser page.

typescript hello world program for beginners
typescript hello world program for beginners

Conclusion

In this Typescript tutorial, we got basic information, like what is typescript, why we need typescript, and how it is better than javascript, we saw by discussing an issue. Moreover, we set up the typescript development environment, and create our first hello world program in typescript. Here are the topics we covered:

  • What is typescript?
  • Why do we use typescript?
  • Advantages of Typescript over JavaScript
  • Set up the Typescript development environment
  • First Hello World with Typescript

You may like the following typescript tutorials:

>