DEV Community

Cover image for Getting to Know TypeScript - : A Beginner's Guide
Benson Thomas
Benson Thomas

Posted on • Edited on

Getting to Know TypeScript - : A Beginner's Guide

Welcome to the world of TypeScript! If you're here, chances are you're familiar with JavaScript and are looking to enhance your skills with TypeScript, a powerful superset of JavaScript. TypeScript adds static typing to JavaScript, helping you catch errors early and write more maintainable code.

What is TypeScript?

TypeScript is an open-source language developed by Microsoft that builds on JavaScript by adding static type definitions. These types help catch errors during development, leading to more robust and reliable code. Unlike JavaScript, TypeScript code needs to be compiled into JavaScript before it can be run in the browser or Node.js runtime.

Setting Up TypeScript

Before you start, ensure you have Node.js installed on your machine. You can download it from nodejs.org

Installation

To install TypeScript, you can use npm (Node Package Manager). Open your terminal and run:

npm install -g typescript
Enter fullscreen mode Exit fullscreen mode

This command installs TypeScript globally on your machine, making the tsc (TypeScript compiler) command available.

Initializing a TypeScript Project

Navigate to your project directory and run:
Let's start with a simple example. Create a new file called index.ts:

function greet(name: string): string {
    return `Hello, ${name}!`;
}

const user = 'World';
console.log(greet(user));
Enter fullscreen mode Exit fullscreen mode

In this code, we define a greet function that takes a name parameter of type string and returns a string. The : string after the parameter and the function name is TypeScript's way of defining types.

Compiling TypeScript

To compile your TypeScript code to JavaScript, run:

tsc
Enter fullscreen mode Exit fullscreen mode

This command reads the tsconfig.json file and compiles the index.ts file into index.js. You can then run the generated JavaScript file using Node.js:

node index.js
Enter fullscreen mode Exit fullscreen mode

You should see the output:

Hello, World!
Enter fullscreen mode Exit fullscreen mode

Congratulations! You've taken your first steps into TypeScript. On your first day, you've learned how to set up TypeScript, write and compile basic code.

We will dive more into typescript language in the upcoming blogs, so kindly follow me to get updated with my blogs.

Thanks for reading.

Happy coding!

Top comments (0)