"Mastering TypeScript: From Loose to Strong Typing" Part: 01

"Mastering TypeScript: From Loose to Strong Typing" Part: 01

A Practical Guide to TypeScript's Data Types

Understanding TypeScript: A Brief Introduction

Programming languages like JavaScript are popular for having a loose typing system that allows for flexibility but frequently results in runtime mistakes. In contrast, TypeScript offers a sophisticated type system and a more organized, methodical approach to writing code. This post will discuss type unions and functions, go over the idea of strong typing, and examine some of the fundamental data types in TypeScript.

Strong Typing in TypeScript

TypeScript is a "strongly typed" language in the sense that tight type checking is enforced both at compile and runtime. TypeScript detects type-related mistakes early in the development process, during compilation, in contrast to JavaScript, where types are computed dynamically at runtime. This lowers the possibility of unanticipated runtime problems and improves code reliability.

Basic Data Types in TypeScript

Variables in TypeScript provide the option to be explicitly allocated a particular data type, which increases code behavior predictability. Let's examine a few fundamental data types:

1. String, Number, and Boolean

let myName = "Bharat";
myName = 43; 
 Compiler error: Type 'number' is not assignable to type 'string'
myName = "ajay"; 
 Works fine, similar to JavaScriptExplicitly Defined Types

2 Explicitly Defined Types

let userName: string = "user";
let userAddress: string;
userAddress = "andheri east";

let userId: number = 43;
let isValid: boolean = true;
let userPan: any;
userPan = "BUDP";
userPan = "8308";
userPan = true

The any type allows flexibility but should be used cautiously, as it sacrifices some of TypeScript's benefits.

3 Union

Union Variables in TypeScript provide the option to be explicitly allocated a particular data type, which increases code behavior predictability. Let's examine a few fundamental data types.

How Type Unions Work

let schoolId: string | number;
schoolId = "Bharat";
schoolId = 234;

The type union string | number is used to declare schoolId in this sample. This implies that values of type string or type number may be set to schoolId. It is initially given the string value "Bharat," and then subsequently it is given the numerical value 234. This flexibility is welcomed by TypeScript, which makes sure the variable stays inside the designated data types.

Accepting Multiple Input Types:

In situations where data may arrive in multiple formats, type unions excel. For example, depending on the situation, a property in an API response can be either a string or a number.

function displayId(id: string | number) {
    console.log("ID:", id);
}

TypeScript type unions enable programmers to create more flexible and durable code. Accepting the flexibility of type unions allows you to work with a variety of data scenarios while maintaining the advantages of strong typing, which enhances the overall stability and maintainability of your TypeScript applications.

Type-Checked Functions in TypeScript: Ensuring Code Integrity

The strength of strong typing in TypeScript flows naturally into functions, providing developers with a powerful tool to ensure that parameters and return values have the correct data types. This improved type checking level makes a major contribution to your code's overall integrity.

Declaring Typed Functions

Let's examine a couple of examples:

const sum = (a: number, b: number) => a + b;
// returns type number

In this case, the function sum returns a result of the same type after accepting two parameters of the same type, a and b. In order to avoid potential runtime issues, TypeScript makes sure that any attempt to call this function with incompatible types will be detected during compilation.

const sum = (a: number, b: string) => a + b;
//returns type string

Here, the function sumTwo deviates from the previous example by accepting a number and a string and returning a string. TypeScript's static typing steps in to catch any potential issues early in the development process. If there's an attempt to add a number to a string, the compiler will raise an error, alerting the developer to the type mismatch.

summarized: Writing code is more organized and secure thanks to TypeScript's robust typing. Embracing type unions, explicit data types, and type-checked functions can help developers create software that is more dependable and easier to maintain. This short introduction merely touches the surface of TypeScript's features, which make it an invaluable tool for contemporary web development.