DEV Community

Cover image for Getting Started with TypeScript: A Comprehensive Guide
Jack Pritom Soren
Jack Pritom Soren

Posted on

Getting Started with TypeScript: A Comprehensive Guide

Introduction

TypeScript is a superset of JavaScript that brings static typing to the language. Developed by Microsoft, it aims to enhance the development experience by catching errors during development rather than at runtime. TypeScript code is transpiled to JavaScript, making it compatible with all JavaScript environments. In this guide, we will delve into various aspects of TypeScript, starting from its installation to more advanced concepts like inheritance and generics.

Installation

To get started with TypeScript, you first need to install it. You can use npm (Node Package Manager) to install TypeScript globally using the following command:

npm install -g typescript
Enter fullscreen mode Exit fullscreen mode

This installs the TypeScript compiler (tsc), which you can use to compile your TypeScript code into JavaScript.

How TypeScript Works

TypeScript adds a static type-checking layer on top of JavaScript. This means that during development, TypeScript checks for type errors and provides meaningful feedback, enabling developers to catch potential issues early in the development process. After development, the TypeScript code is transpiled into JavaScript, which can then be run on any JavaScript runtime.

TypeScript Configuration

TypeScript projects often include a tsconfig.json file, which contains configuration options for the TypeScript compiler. This file allows you to specify compiler options, include or exclude files, and define the project's structure.

Example tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}
Enter fullscreen mode Exit fullscreen mode

Data Types

Built-in Data Types

Number

The number type represents both integer and floating-point numbers.

let age: number = 25;
let price: number = 29.99;
Enter fullscreen mode Exit fullscreen mode

String

The string type is used to represent textual data.

let name: string = "John";
Enter fullscreen mode Exit fullscreen mode

Boolean

The boolean type represents true/false values.

let isStudent: boolean = true;
Enter fullscreen mode Exit fullscreen mode

Undefined

The undefined type is used for variables that have been declared but not assigned a value.

let undefinedVar: undefined;
Enter fullscreen mode Exit fullscreen mode

Null

The null type represents an intentional absence of any object value.

let nullVar: null = null;
Enter fullscreen mode Exit fullscreen mode

Void

The void type is often used as the return type of functions that do not return a value.

function logMessage(): void {
  console.log("Hello, TypeScript!");
}
Enter fullscreen mode Exit fullscreen mode

User-Defined Data Types

Arrays

Arrays allow you to store multiple values of the same type.

let numbers: number[] = [1, 2, 3, 4, 5];
Enter fullscreen mode Exit fullscreen mode

Enums

Enums are a way to organize and represent a set of named values.

enum Color {
  Red,
  Green,
  Blue
}

let myColor: Color = Color.Green;
Enter fullscreen mode Exit fullscreen mode

Classes

Classes provide a blueprint for creating objects with methods and properties.

class Person {
  constructor(public name: string) {}
}

let person = new Person("Alice");
Enter fullscreen mode Exit fullscreen mode

Interfaces

Interfaces define the structure of objects and can be used to enforce a specific shape on objects.

interface Shape {
  area(): number;
}

class Circle implements Shape {
  constructor(private radius: number) {}
  area(): number {
    return Math.PI * this.radius ** 2;
  }
}
Enter fullscreen mode Exit fullscreen mode

Tuple Data Type

Tuples allow you to express an array where the type of a fixed number of elements is known.

let person: [string, number] = ["John", 30];
Enter fullscreen mode Exit fullscreen mode

Enum Data Type

Enums allow you to create a set of named constant values.

enum Direction {
  Up,
  Down,
  Left,
  Right
}

let playerDirection: Direction = Direction.Up;
Enter fullscreen mode Exit fullscreen mode

Object Data Type

Objects in TypeScript can have a specific shape defined by interfaces or types.

interface Person {
  name: string;
  age: number;
}

let person: Person = { name: "Alice", age: 25 };
Enter fullscreen mode Exit fullscreen mode

Custom Data Type

You can create custom types using the type keyword.

type Point = { x: number; y: number };

let point: Point = { x: 10, y: 20 };
Enter fullscreen mode Exit fullscreen mode

Class Typescript

Classes are a fundamental part of object-oriented programming in TypeScript.

class Animal {
  constructor(public name: string) {}
  makeSound(): void {
    console.log("Some generic sound");
  }
}

let cat = new Animal("Fluffy");
cat.makeSound(); // Output: Some generic sound
Enter fullscreen mode Exit fullscreen mode

Inheritance

Inheritance allows a class to inherit properties and methods from another class.

class Dog extends Animal {
  makeSound(): void {
    console.log("Woof! Woof!");
  }
}

let dog = new Dog("Buddy");
dog.makeSound(); // Output: Woof! Woof!
Enter fullscreen mode Exit fullscreen mode

Abstract Class

Abstract classes cannot be instantiated and are often used as base classes.

abstract class Shape {
  abstract area(): number;
}

class Circle extends Shape {
  constructor(private radius: number) {
    super();
  }

  area(): number {
    return Math.PI * this.radius ** 2;
  }
}
Enter fullscreen mode Exit fullscreen mode

Encapsulation

Encapsulation involves bundling the data (attributes) and methods (functions) that operate on the data into a single unit, i.e., a class.

class BankAccount {
  private balance: number = 0;

  deposit(amount: number): void {
    this.balance += amount;
  }

  withdraw(amount: number): void {
    if (amount <= this.balance) {
      this.balance -= amount;
    } else {
      console.log("Insufficient funds");
    }
  }

  getBalance(): number {
    return this.balance;
  }
}

let account = new BankAccount();
account.deposit(1000);
account.withdraw(500);
console.log(account.getBalance()); // Output: 500
Enter fullscreen mode Exit fullscreen mode

Function Signature

Function signatures define the structure of a function, including its parameters and return type.

type AddFunction = (a: number, b: number) => number;

let add: AddFunction = (a, b) => a + b;
console.log(add(3, 5)); // Output: 8
Enter fullscreen mode Exit fullscreen mode

Interface

Interfaces define contracts for objects, specifying the properties and methods they must have.

interface Printable {
  print(): void;
}

class Document implements Printable {
  print(): void {
    console.log("Printing document...");
  }
}

let document: Printable = new Document();
document.print(); // Output: Printing document...
Enter fullscreen mode Exit fullscreen mode

Generic Type

Generics allow you to create reusable components that can work with a variety of data types.

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

let result: number = identity(42);
Enter fullscreen mode Exit fullscreen mode

This comprehensive guide covers the fundamental concepts of TypeScript, from installation to advanced features like generics and encapsulation. By leveraging TypeScript's static typing and object-oriented capabilities, developers can build more

robust and maintainable JavaScript applications. Whether you're a beginner or an experienced developer, TypeScript opens up new possibilities for writing scalable and error-resistant code.

Follow me on : Github Linkedin

Top comments (3)

Collapse
 
jwhenry3 profile image
Justin Henry

Another unit of information that is very helpful is Union Typing, which allows you to merge types without dealing with inheritance.

export declare type Truck = { extendedCab: boolean };
export declare type Car = { trunkSize: 'small' | 'medium' | 'large' };
export declare type Vehicle = Truck | Car; 
// can be one or the other

export declare type NameLike = { name: string };
export declare type AgeLike = { age: number };
export declare type PersonLike = NameLike & PersonLike; 
// requires both fields
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jps27cse profile image
Jack Pritom Soren

Thank you so much!

Collapse
 
jangelodev profile image
João Angelo

Hi Jack Pritom Soren !
Thanks for sharing