TypeScript Tutorials for Beginners [Typescript Basics]

Welcome to these comprehensive TypeScript tutorials! Whether you’re just starting out or looking to deepen your understanding, you’re in the right place. In this tutorial, I will help you learn TypeScript, a powerful superset of JavaScript that brings static typing and other advanced features to the table. We’ll walk through the basics, set up your environment, and write your first TypeScript program together. By the end of this guide, you’ll have a solid grasp of TypeScript and be ready to use it in your projects.

What is TypeScript?

TypeScript is a superset of JavaScript, meaning it builds on JavaScript by adding new features and capabilities. It was developed by Microsoft to address some of JavaScript’s limitations, particularly in large-scale applications.

One of the key features of TypeScript is static typing, which allows developers to catch errors at compile time rather than at runtime, making code more robust and maintainable.

Check out

Why Use TypeScript?

Here are a few reasons why we use TypeScript.

  1. Static Typing: TypeScript allows you to define types for variables, function parameters, and return values, catching type-related errors early.
  2. Enhanced IDE Support: TypeScript provides better autocompletion, navigation, and refactoring support in modern IDEs like Visual Studio Code.
  3. Improved Code Quality: TypeScript’s type system helps you write cleaner and more predictable code.
  4. Compatibility: TypeScript code compiles to plain JavaScript, making it compatible with any JavaScript environment.

Check out How to Use Try Catch in TypeScript? and How to Handle Catch Error Types in TypeScript?

Set Up Your TypeScript Environment

Now, let me explain how to set up the TypeScript environment step by step.

Step 1: Install Node.js and npm

To get started with TypeScript, you must install Node.js and npm (Node Package Manager) on your machine. You can download and install them from the official Node.js website.

Step 2: Install TypeScript

Once you have Node.js and npm installed, you can install TypeScript globally on your machine by running the following command in your terminal:

npm install -g typescript

Step 3: Verify Installation

To verify that TypeScript is installed correctly, you can check the version by running:

tsc --version

If everything is set up correctly, you should see the version number of TypeScript.

Step 4: Set Up Visual Studio Code

Visual Studio Code (VSCode) is a popular code editor that supports TypeScript. You can download it from the official VSCode website. Once installed, you can enhance your TypeScript development experience by installing the TypeScript extension from the VSCode marketplace.

This is so simple to set up the TypeScript environment for development.

Write Your First TypeScript Program

Now, in the next step to learn as a beginner, you should know how to write your first TypeScript program.

Follow the below steps.

Step 1: Create a New Project

Create a new directory for your TypeScript project and navigate into it:

mkdir my-typescript-project
cd my-typescript-project

Step 2: Initialize a TypeScript Project

Initialize a new TypeScript project by running:

tsc --init

This command generates a tsconfig.json file, which contains configuration options for the TypeScript compiler.

Step 3: Create a TypeScript File

Create a new file named index.ts in your project directory:

touch index.ts

Step 4: Write TypeScript Code

Open index.ts in your code editor and write the following code:

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

let userName: string = "John";
console.log(greet(userName));

In this example, we define a greet function that takes a name parameter of type string and returns a greeting message. We then declare a variable userName of type string and call the greet function with userName as the argument.

Step 5: Compile TypeScript to JavaScript

To compile your TypeScript code to JavaScript, run the following command in your terminal:

tsc

This command compiles all .ts files in your project according to the settings in tsconfig.json. By default, it generates a corresponding .js file for each .ts file.

Step 6: Run the Compiled JavaScript

You can now run the compiled JavaScript file using Node.js:

node index.js

You should see the output:

Hello, John!

Check out

Basic Types in TypeScript

TypeScript enhances JavaScript by adding static types, which allows you to explicitly declare the types of variables, function parameters, and return values. This helps catch errors early during development and makes the code more readable and maintainable. Let’s dive deeper into the basic types available in TypeScript with detailed explanations and examples.

Number

The number type in TypeScript is used to represent both integer and floating-point values. It supports decimal, hexadecimal, binary, and octal literals.

Example

let age: number = 30; // Decimal
let hex: number = 0x1a; // Hexadecimal
let binary: number = 0b1010; // Binary
let octal: number = 0o23; // Octal

console.log(age); // 30
console.log(hex); // 26
console.log(binary); // 10
console.log(octal); // 19

String

The string type is used to represent textual data. You can use single quotes ('), double quotes ("), or backticks (`) for string literals. Backticks allow for template strings, which can include embedded expressions.

Example

let firstName: string = "Jane";
let lastName: string = 'Doe';
let fullName: string = `${firstName} ${lastName}`;

console.log(firstName); // Jane
console.log(lastName); // Doe
console.log(fullName); // Jane Doe

Boolean

The boolean type represents logical values: true or false.

Example

let isStudent: boolean = true;
let hasGraduated: boolean = false;

console.log(isStudent); // true
console.log(hasGraduated); // false

Array

The array type can be declared in two ways: using the type followed by [], or using the generic Array<type> syntax.

Example

let hobbies: string[] = ["Reading", "Traveling", "Cooking"];
let scores: Array<number> = [95, 88, 76];

console.log(hobbies); // ["Reading", "Traveling", "Cooking"]
console.log(scores); // [95, 88, 76]

Tuple

A tuple type allows you to express an array with a fixed number of elements whose types are known but can be different.

Example

let person: [string, number] = ["John", 25];

console.log(person); // ["John", 25]
console.log(person[0]); // John
console.log(person[1]); // 25

Enum

Enums allow you to define a set of named constants. TypeScript provides both numeric and string-based enums.

Example

enum Color {
    Red,
    Green,
    Blue
}

let favoriteColor: Color = Color.Green;

console.log(favoriteColor); // 1 (since enums are zero-based by default)
console.log(Color[1]); // Green

// String Enum
enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT"
}

let move: Direction = Direction.Up;

console.log(move); // UP

Any

The any type is a powerful way to work with existing JavaScript. It allows you to opt out of type checking for a variable.

Example

let randomValue: any = "Hello";
randomValue = 42;
randomValue = true;

console.log(randomValue); // true

Void

The void type is used to indicate that a function does not return a value.

Example

function logMessage(message: string): void {
    console.log(message);
}

logMessage("This is a message."); // This is a message.

Null and Undefined

TypeScript has two special types, null and undefined, which have their own types respectively. By default, null and undefined are subtypes of all other types.

Example

let u: undefined = undefined;
let n: null = null;

console.log(u); // undefined
console.log(n); // null

Never

The never type represents the type of values that never occur. For instance, a function that always throws an error or a function that never returns.

Example

function throwError(message: string): never {
    throw new Error(message);
}

function infiniteLoop(): never {
    while (true) {}
}

Object

The object type represents non-primitive types, i.e., anything that is not number, string, boolean, symbol, null, or undefined.

Example

let person: object = { name: "John", age: 25 };

console.log(person); // { name: "John", age: 25 }

Working with Interfaces

Interfaces in TypeScript allow you to define the structure of an object. They provide a way to enforce the shape of an object and ensure that it has the required properties.

Example

interface Person {
    firstName: string;
    lastName: string;
    age: number;
    greet(): string;
}

let person: Person = {
    firstName: "Alice",
    lastName: "Johnson",
    age: 28,
    greet: function (): string {
        return `Hello, my name is ${this.firstName} ${this.lastName}.`;
    }
};

console.log(person.greet());

In this example, we define an interface Person with properties firstName, lastName, age, and a method greet. We then create an object person that adheres to the Person interface.

Advanced TypeScript Features

Generics

Generics allow you to create reusable components that can work with a variety of types. They provide a way to create functions, classes, and interfaces that can operate on different types without sacrificing type safety.

Example

function identity<T>(arg: T): T {
    return arg;
}

let output1 = identity<string>("Hello");
let output2 = identity<number>(42);

In this example, we define a generic function identity that takes an argument of type T and returns a value of the same type. We then call the function with different types.

Modules

Modules in TypeScript allow you to organize your code into reusable and maintainable pieces. You can export and import classes, interfaces, functions, and variables from one module to another.

Example

// math.ts
export function add(a: number, b: number): number {
    return a + b;
}

// main.ts
import { add } from './math';

console.log(add(5, 3));

In this example, we define a function add in a module math.ts and export it. We then import the add function in main.ts and use it.

TypeScript Tutorials for Beginners

Here is the list of TypeScript tutorials for beginners.

Conclusion

By following this step-by-step guide, I hope you have learned how to set up a TypeScript environment, write and compile TypeScript code, and use some of the basic and advanced features of TypeScript. I hope this tutorial helps you to start with TypeScript as a beginner.

TypeScript Control Statement Tutorials

Here is the list of TypeScript control statement tutorials: