Typescript

TypeScript is an open-source programming language developed by Microsoft. It is a superset of JavaScript, meaning that any valid JavaScript code is also valid TypeScript code. TypeScript adds static types, classes, and interfaces to JavaScript, making it more suitable for large-scale applications and providing better tooling for developers.


Installation and Setup

To get started with TypeScript, you'll need to install TypeScript globally using a package manager.

bash
pnpm install -g typescript // or pnpm install -D typescript@beta //for last updates in a specific project

You can use the tsc command followed by the file name to compile TypeScript files:

bash
tsc myfile.ts

Alternatively, you can create a tsconfig.json file to configure a development environment:

bash
tsc --init


Tsconfig.json setup:

  • Set the module and rootDir for the project in the Modules configuration:

    json
    /* Modules */ "module": "commonjs" /* Specify what module code is generated. */, "rootDir": "./src" /* Specify the root folder within your source files. */,

  • Set the outDir and removeComments in the Emit configuration:

    json
    /* Emit */ "outDir": "./dist" /* Specify an output folder for all emitted files. */, "removeComments": true /* Disable emitting comments. */, "noEmitOnError": true /* Disable emitting files if any type checking errors are reported. */,

  • Make sure the strict mode is set to true in the Type Cheking configuration:

    json
    /* Type Checking */ "strict": true /* Enable all strict type-checking options. */,


Node environment setup:

  • Install TypeScript type declarations for Node.js.

    bash
    pnpm install -D @types/node

  • Install ts-node and nodemon dev dependencies:

    bash
    pnpm i ts-node nodemon -D

  • Set the scripts to initialize TypeScript.

    json
    "scripts": { "start": "tsc && node ./dist/index.js", "ts-node": "ts-node index.ts", "dev": "nodemon index.ts" },


Debugger setup

  • Make sure to set the sourceMap to true in the Emit configuration:

    json
    "sourceMap": true /* Create source map files for emitted JavaScript files. */,

  • Execute the TypeScript compiler:

    bash
    tsc

  • Create the launch.json file and set the preLaunchTask to build over the Tsconfig.json:

    json
    { "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "skipFiles": ["<node_internals>/**"], "program": "${workspaceFolder}\\src\\index.ts", "preLaunchTask": "tsc: build - tsconfig.json", // Set this line in the configuration "outFiles": ["${workspaceFolder}/**/*.js"] } ] }


Basic Types

TypeScript has a few basic types to help you define your variables:


  • boolean: Represents true or false
  • number: Represents a numeric value
  • string: Represents a sequence of characters
  • array: Represents a collection of elements
  • tuple: Represents an ordered list of elements with specific types
  • enum: Represents a collection of named constants
  • any: Represents any type (use with caution)
  • void: Represents the absence of a type, commonly used for functions that don't return a value
  • null and undefined: Represent the absence of a value

tsx
let isActive: boolean = true; let age: number = 30; let name: string = "John Doe"; let list: number[] = [1, 2, 3]; let tuple: [string, number] = ["age", 30]; enum Color {Red, Green, Blue} let favoriteColor: Color = Color.Green;

Interfaces

Interfaces are used to define the structure of an object. They help with code completion and type checking.

tsx
interface Person { name: string; age: number; greet(): void; } let john: Person = { name: "John Doe", age: 30, greet() { console.log(`Hello, my name is ${this.name}`); } }; john.greet(); // Hello, my name is John Doe

Classes

TypeScript supports classes, inheritance, and access modifiers (public, private, and protected).

tsx
class Animal { protected name: string; constructor(name: string) { this.name = name; } speak(): void { console.log(`${this.name} makes a noise.`); } } class Dog extends Animal { constructor(name: string) { super(name); } speak(): void { console.log(`${this.name} barks.`); } } const dog = new Dog("Rex"); dog.speak(); // Rex barks.

Functions

Functions in TypeScript can have typed parameters and return types.

tsx
function greet(name: string): string { return `Hello, ${name}`; } console.log(greet("John")); // Hello, John // Optional parameters function sayHello(name?: string): string { return name ? `Hello, ${name}` : "Hello"; } console.log(sayHello()); // Hello // Default parameters function welcome(name: string = "Guest"): string { return `Welcome, ${name}`; } console.log(welcome()); // Welcome, Guest


Generics

Generics allow you to create reusable components that work with different types.

tsx
function identity<T>(arg: T): T { return arg; } let output1 = identity<string>("Hello"); let output2 = identity<number>(42); // Generic interfaces interface GenericIdentityFn<T> { (arg: T): T; } let myIdentity: GenericIdentityFn<number> = identity; ```<br/> <br/> # Modules TypeScript supports importing and exporting modules using the ES6 module syntax. <Color type="accent">example.ts</Color> ```tsx export function exampleFunction(): string { return "This is an example function."; }

main.ts
tsx
import { exampleFunction } from "./example"; console.log(exampleFunction()); // This is an example function.

Compile and run the code:

bash
tsc main.ts node main.js