Static Type Checking in JavaScript with TypeScript


JavaScript is a popular programming language known for its flexibility and dynamic nature. However, this flexibility can sometimes lead to unexpected errors and bugs in large-scale applications. To address this issue, TypeScript was introduced as a superset of JavaScript that provides static type checking capabilities. In this article, we will explore the basics of static type checking in JavaScript using TypeScript, along with code examples and explanations to help you get started.

What is Static Type Checking?

Static type checking is a process where types are associated with variables, function parameters, and function return values at compile-time, rather than at runtime. This allows the compiler to detect type errors before the code is executed, reducing the chances of runtime errors and improving code quality.

TypeScript: Bringing Static Typing to JavaScript

TypeScript extends the syntax of JavaScript to support static typing. It introduces new syntax and constructs that enable developers to define types explicitly. By using TypeScript, you can catch type errors during development, benefit from better code editor support, and improve overall code maintainability.

Installing TypeScript

To get started with TypeScript, you need to have Node.js and npm (Node Package Manager) installed on your system.

You can install TypeScript globally using the following command −

npm install -g typescript

Once TypeScript is installed, you can use the tsc command to compile TypeScript code into JavaScript.

Declaring Variables with Types

In TypeScript, you can explicitly declare the types of variables using the :type syntax.

Example 

Let's consider an example where we want to declare a variable message of type string −

let message: string = "Hello, TypeScript!";
console.log(message);

Explanation

In this code snippet, we declare the variable message as a string using the :string syntax. The compiler will enforce that only string values can be assigned to this variable.

Output

The output of this code will be −

Hello, TypeScript!

Function Declarations with Types

TypeScript allows you to define types for function parameters and return values.

Example 

Let's see an example of a simple function that adds two numbers together −

function addNumbers(num1: number, num2: number): number {
   return num1 + num2;
}

let result: number = addNumbers(10, 5);
console.log(result);

Explanation

In this code, the addNumbers function takes two parameters of type number and returns a value of type number. The variables num1, num2, and result are explicitly typed as numbers.

Output

The output of this code will be −

15

Type Inference

TypeScript has a powerful type inference mechanism that can automatically deduce the types of variables based on their assigned values.

Example 

let age = 25;
console.log(typeof age);

let name = "John";
console.log(typeof name);

In this code, we don't explicitly declare the types of age and name. However, TypeScript infers their types based on the assigned values.

Interfaces and Type Annotations

TypeScript provides interfaces to define custom types. An interface defines the structure of an object, including the names and types of its properties. Let's consider an example where we define an interface for a user object.

Example 

interface User {
   id: number;
   name: string;
   email: string;
}

let user: User = {
   id: 1,
   name: "John Doe",
   email: "john@example.com",
};

console.log(user);

Explanation

In this code, we define an interface called User with three properties: id, name, and email. We then declare a variable user of type User and assign an object that adheres to the interface structure.

Output

The output of this code will be −

{ id: 1, name: 'John Doe', email: 'john@example.com' }

Union Types

Consider the code shown below.

function displayResult(result: string | number): void {
  console.log("Result:", result);
}

displayResult("Success"); 
displayResult(200); 

Explanation

In this example, the displayResult function takes a parameter that can be either a string or a number. This is achieved by using a union type (string | number) in the function signature.

Type Aliases

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

function calculateDistance(point1: Point, point2: Point): number {
   const dx = point2.x - point1.x;
   const dy = point2.y - point1.y;
   return Math.sqrt(dx * dx + dy * dy);
}  

const p1: Point = { x: 0, y: 0 };
const p2: Point = { x: 3, y: 4 };

console.log(calculateDistance(p1, p2));

Explanation

In this example, we define a type alias Point for an object with x and y properties. The calculateDistance function takes two Point objects as parameters and calculates the distance between them using the Pythagorean theorem.

Output

5

Conclusion

Static type checking with TypeScript brings numerous benefits to JavaScript development, including catching type errors early, improving code editor support, and enhancing code maintainability. By adopting TypeScript, developers can write safer and more reliable code while still enjoying the flexibility and dynamic nature of JavaScript.

In this article, we explored the basics of static type checking in JavaScript with TypeScript, including variable declarations, function declarations, type inference, interfaces, union types, and type aliases. Armed with this knowledge, you can now start using TypeScript to build robust and scalable JavaScript applications.

Updated on: 25-Jul-2023

345 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements