#AD Top Online Web Development & Programming Courses | Udemy
Newsletter Screenshot

TypeScript basics tutorial – Hello World!

Last modified September 14th 2021 | | #typescript

TypeScript is a strict syntactical superset of JavaScript with optional typing. It compiles to plain JavaScript which means existing JavaScript is also valid TypeScript. Because of this you can add TypeScript to a project incrementally as you learn. In this quick tutorial we’ll cover some TypeScript basics to get you up and running.

First let’s install TypeScript globally by running the following NPM command:

npm install -g typescript

Next create a new TypeScript file called app.ts with the following function:

const firstName : string = "Michael";
const helloWorld = (firstName : string): string => {
  return `Hello, World! My name is ${firstName}.`;
};
console.log(helloWorld(firstName));Code language: JavaScript (javascript)

Here we have used type annotations to declare that the fisrtName provided must be a string and that the data returned from helloWorld is a string. Once an entity (variable, function, object…) has a type annotation declared its type cannot be changed, this ensures types remain consistent.

We can now compile our TypeScript file by running the following command:

tsc app.tsCode language: CSS (css)

This create’s a new app.js file with compiled JavaScript as follows:

var firstName = "Michael";
var helloWorld = function (firstName) {
    return "Hello, World! My name is " + firstName + ".";
};
console.log(helloWorld(firstName));Code language: JavaScript (javascript)

This has compiled as ES5 (current default) with all the TypeScript removed.

Now if we change firstName to something other than a string, for example:

const firstName : string = true;Code language: JavaScript (javascript)

When compiled you’ll get the following error message due to the type mismatch:

Argument of type 'boolean' is not assignable to parameter of type 'string'.Code language: JavaScript (javascript)

Whilst you’re not required to use type annotations in TypeScript checking types helps avoid errors when dealing with different data types. They also make code more readable and easier to maintain especially in larger more complex applications.

That’s all for this tutorial. You should now have an understanding of how to compile a TypeScript file and how to use type annotations to prevent type mismatches. Thanks for reading and stay tuned for more TypeScript tutorials in the coming months.

#AD Shop Web Developer T-Shirts