TypeScript

Introduction

Welcome to the world of TypeScript, a powerful superset of JavaScript that has been making waves in the development community. Whether you're a beginner taking your first steps into programming or an intermediate developer looking to expand your skill set, this article is your gateway to understanding and harnessing the capabilities of TypeScript.

We'll start with the basics, exploring the fundamental syntax and features that set TypeScript apart. From there, we'll delve into object-oriented programming concepts, discovering how TypeScript enhances familiar JavaScript principles. As we journey through the realms of TypeScript, we'll cover advanced topics like generics and decorators, equipping you with the knowledge to write more robust and scalable code. Along the way, we'll explore real-world examples and case studies, showcasing the practical applications of TypeScript in various projects. Whether you're setting up TypeScript for the first time, debugging your code, or integrating it into existing projects, this comprehensive guide has you covered. So, buckle up as we embark on a journey through the world of TypeScript, unlocking its potential and empowering you to write more maintainable and efficient code.

What will be present:

Brief History

Features

Setup

npm

To get started, you'll need Node.js, which includes npm (Node Package Manager). To initialize a Node.js project, run the following command in your project root directory:

npm init -y

This creates a package.json file to manage your project's dependencies and share it with others.

TypeScript Installation

TypeScript can be installed in two ways: locally or globally.

Locally (recommended)

npm install typescript --save-dev

This command installs TypeScript in the current project directory as a development dependency. The TypeScript compiler (tsc) can be accessed using npm scripts defined in your package.json file.

Local installation ensures that everyone working on the project is using the same version of TypeScript.

Globally

npm install -g typescript

This command installs TypeScript globally on your system. This means you can access the TypeScript compiler (tsc) from any directory on your system.

Global installation could lead to versioning issues if different projects rely on different versions of TypeScript.

tsconfig

A tsconfig.json file provides configuration options for the TypeScript compiler. It allows you to specify things like the target JavaScript version, module system, and output directory. Having a tsconfig.json file ensures that your TypeScript code is compiled consistently across different environments.

The following is an example of a basic tsconfig.json file:

{
      "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "outDir": "./dist"
      }
    }

Alternatively, you can generate a tsconfig.json file with all possible compiler options commented out, by running the tsc --init command. Since this generated file contains a lot of information though, it can be overwhelming for beginners.

Writing and Compiling TypeScript

After setting up TypeScript for your project, you can now start writing and compiling TypeScript code to enjoy the benefits of type checking and static analysis. For this demo, lets write a basic hello-world program.

  1. Create a new file with a .ts extension (e.g. hello.ts)
  1. Write the following hello-world program
    let message: string = 'Hello World!';
        console.log(message);
  1. Navigate to the directory where hello.ts is located in your terminal
  1. Use the tsc compiler to compile the TypeScript file into JavaScript
    npx tsc hello.ts
  1. Open hello.js. Notice how it doesn't look very different from hello.ts
    var message = 'Hello World!';
        console.log(message);
  1. Run the compiled JavaScript code
    node hello.js

TypeScript Type

TypeScript Tupel

Tuple is similar to array but their elements can have different types. All the elements types must be declared in order in the declaration. Example: const t2:[string, number, boolean] = ['Manu', 100, true];

TypeScript Never

It represents the type of values that never occur. A function that returns nothing can have return type as void. However a function that never returns (or always throws) can have return type as never. Example: let bar: never = (() => { throw new Error('Error!') })();

TypeScript typeof operator

TypeScript typeof operator is used to get the type of a variable as string. Example:

            let strOrNum: string | boolean ;
                if(typeof strOrNum === "string") {
                    strOrNum = 'Hello';         }
                if(typeof strOrNum === "boolean") {
                    strOrNum = true;        }

TypeScript Classes

Using class keyword:
           class ClassName{
                //constructor;
                //field;
                //method;
Example:
            class Box {
                legth: number;
                width: number;          
                constructor(legth: number, width: number) {            
                    this.legth = legth;            
                    this.width = width;          
                }
                add(box: Box) {           
                    return new Box(this.legth + box.legth, this.width + box.width);           
                } }

TypeScript v.s. JavaScript

TypeScript v.s. Other Languages

FeatureTypeScriptPythonPHPC
Type SystemStaticDynamicDynamicStatic
TranslatorTranspiler (tsc) to JavaScriptInterpreterInterpreterCompiler
BindingEarly binding (static binding)Late binding (dynamic binding)Late binding (dynamic binding)Early binding (static binding)
VisibilityPublic, private, protectedPublic, private, protectedPublic, private, protectedPublic, private, static
ScopingBlock-scoped and function-scopedBlock-scoped and function-scopedFunction-scopedBlock-scoped and function-scoped
Lifetime ManagementAutomatic garbage collectionAutomatic garbage collectionAutomatic garbage collectionManual memory management
InterfacesSupports interfaces to define the structure of objectsDoes not have built-in support for interfaces, but can be emulated using abstract classesDoes not have built-in support for interfaces, but can be emulated using abstract classesDoes not have built-in support for interfaces
GenericsSupports generics to write reusable code that works with different data typesDoes not have built-in support for genericsDoes not have built-in support for genericsDoes not have built-in support for generics
Parameter-PassingSupports both pass-by-value and pass-by-reference parameter passingSupports pass-by-object parameter passing, which is similar to pass-by-referenceSupports pass-by-reference parameter passingSupports pass-by-value parameter passing
MetapogrammingSupports decorators and reflectionStrong support with decorators, metaclasses, and dynamic manipulationLimited support compared to Python, includes reflection and dynamic creationMinimal support; lacks reflection and runtime code generation

Complex example

Group project

Account.java vs Account.ts Customer.java vs Customer.ts CheckingAccount.java vs CheckingAccount.ts SavingAccount.java vs SavingAccount.ts

Resources