Static vs. dynamic or loosely typed language.

  1. Static Languages:

In static languages, once we define a variable and store a number value in it, we cannot assign another type of value to this variable.

e.g.

#include <iostream>
using namespace std;

int main() {
    int number = 5;
    number = "Hello"; // This will cause a compilation error

    cout << number << endl;
    return 0;
}

In the above example, we are trying to assign a string value "Hello" to an integer variable number. This will result in a compilation error because static languages enforce strict type-checking at compile time. Therefore, the type of a variable cannot be changed once it is defined.

  1. Dynamic or Loosely typed languages:

    In loosely typed languages we can change the type of variable throughout.

    E.g.

let number = 5;
number = "Hello";

It is valid in dynamic languages (JavaScript).
Dynamic or loosely typed languages allow us to change a variable's data type.
However, this flexibility can cause problems in large projects, as changing types can lead to errors during runtime.

So In this case We can use TypeScript to prevent the runtime errors, it will throw an error during compilation only.

TypeScript

To prevent such runtime errors we can use TypeScript. TypeScript will add static type-checking to JavaScript. So it will throw an error during compilation if we try to change the variable's type.

let number: number = 5;
number = "Hello"; // This will cause a compilation error

In the above code, TypeScript will throw a compilation error because we are assigning a string to a variable that is declared as a number.