Typescript has emerged as a game changer for developers working with Javasctipt. Typescript is a powerful, open-source language developed by Microsoft. It acts as a superset of Javascript, adding static typing and other features to make javascript development more predictable and maintainable. Here's a comprehensive guide to understanding TypeScript:
Types of languages
1. Strongly typed languages
Strongly typed languages are programming languages that enforce strict type rules, ensuring that operations between mismatched types are not allowed.
Examples - Java, C++, C, Rust
Benefits -
- Lesser runtime error
- Stricter Codebase
- Easy to catch errors at compile time
2. Loosely typed languages
Loosely typed languages, also known as weakly typed languages, do not enforce strict type rules. In these languages, variables can hold values of any type, and operations between mismatched types are often allowed through implicit type conversion (type coercion).
Example - Javascript, Python, php, Perl
Benefits
- Easy To write code
- Flexibility: Developers can write code quickly without worrying about strict type definitions.
💡 People realised that javascript is a very great language, but lacks types. So, typescript comes.
What is Typscript?
TypeScript is a programming language developed and maintained by Microsoft.
It is a strict
syntactical superset
of JavaScript and adds optional static typing to the language.How does typescript code run?
Typescript code never runs in your browser. Your browser can only understand
javascript
. - Javascript is the runtime language (the thing that actually runs in your browser/nodejs runtime)
- Typescript is something that compiles down to javascript
- When typescript is compiled down to javascript, you get
type checking
(similar to C++). If there is an error, the conversion to Javascript fails.
Developers write code in
.ts
files using TypeScript syntax, which includes type annotations, interfaces, and other TypeScript-specific features.TypeScript needs to be converted into JavaScript because browsers and JavaScript runtimes (like Node.js) cannot directly understand TypeScript. This is done using the TypeScript Compiler (
tsc
).Let’s bootstrap a simple Typescript Node.js application locally on our machines
Steps:
- Install TypeScript globally using npm:
npm install -g typescript
- Initialize an empty Node.js project with typescript
mkdir node-app cd node-app npm init -y npx tsc --init
- Create a example.ts file.
const x: number = 1; console.log(x);
- Compile the ts file to js file
tsc -b
- Explore the newly generated example.js file
"use strict"; const x=1; console.log(x);
Now, you can run the example.js file
node example.js
Notice how there is no typescript code in the javascript file. It’s a plain old js file with no
types
If you assign “x” a string value to a variable declared with a different type, TypeScript will show an error during compilation
This is the high level benefit of typescript. It lets you catch
type
errors at compile time
Typescript provides you some basic types
number
, string
, boolean
, null
, undefined
.Try to do it yourself.
Q- Write a function that calculates the sum of two functions
So, Here’s a Tricky Question: Who Decided That We Should Stop Using
var
and Start Saying let
and const
?Ah,
var
... the old faithful! We've all been there, declaring variables with var
like it was the only option in the universe. But then, suddenly—boom!—we get introduced to let
and const
. So, who exactly made that decision? Who thought, "Hey, let’s make JavaScript less wild and introduce some rules around variable declarations"? Well, my friend, it wasn’t just one random person in a coffee shop. It was the ECMAScript Technical Committee (TC39)—a group of coding experts, tech giants, and JavaScript enthusiasts who got together and decided that var
needed a makeover.They came together to fix the issues with var
and make JavaScript a bit more predictable, and voilà, ECMAScript 2015 (ES6) brought us let
and const
.Now back to the typescript
Real-World Use Cases of TypeScript
- Frontend Frameworks like React/Angular
- Backend with Node.js
- Codebases with complex logic or APIs
Interfaces
What are interfaces?
How can you assign types to objects? For example, a user object that looks like this -
const user = { firstName: "tushar", lastName: "agarwal", email: "email@gmail.com". age: 21, }
To assign a type to the
user
object, you can use interfaces
interface User { firstName: string; lastName: string; email: string; age: number; }
Arrays in TS
if you want to access arrays in typescript, it’s as simple as adding a
[]
annotation next to the typeLook at this example u will understand
interface User{ name:string, age:number } function filterAge(user:User[]){ return user.filter(x=>x.age>18); } console.log(filterAge([ { name:"tushar", age:19 }, { name:"keshav", age:14 }, { name:"Ram", age:21 } ])) export default filterAge;
Enums
Enums (short for enumerations) in TypeScript are a feature that allows you to define a set of named constants.
The concept behind an enumeration is to create a human-readable way to represent a set of constant values, which might otherwise be represented as numbers or strings.
enum Status { Pending, Approved, Rejected } function getStatus(status: Status) { if (status === Status.Pending) { console.log("The status is pending."); } } getStatus(Status.Pending); // Works!
Generics
Generics allow you to create reusable components or functions that work with a variety of types, instead of being tied to a specific type. This makes your code more flexible, type-safe, and reusable.
Why Use Generics?
- To write code that works with any data type while preserving type safety.
- To avoid using
any
, which loses type checking.
- To ensure type consistency across function arguments, return values, and data structures.
Problem Statement
Let’s say you have a function that needs to return the first element of an array. Array can be of type either string or integer.
How would you solve this problem?
function getFirstElement(arr: (string | number)[]) { return arr[0]; } const el = getFirstElement([1, 2, 3]);
What is the problem in this approach?
User can send different types of values in inputs, without any type errors
function getFirstElement(arr: (string | number)[]) { return arr[0]; } const el = getFirstElement([1, 2, '3']);
Solution - Generics
Generics enable you to create components that work with any data type while still providing compie-time type safety
function identity<T>(arg:T):T{ return arg; } let output1 = identity<string>("tushar"); let output2 = identity<number>(12);
Real-World Example
Suppose you are building an e-commerce website in which you need a function to fetch products or users generically:
interface User{ id:number, username:string } interface Products{ id:number, name:string } function fetchItems<T>(items:T[]):T[]{ return items; } const users=fetchItems<User>([{id:1,username:"tushar"}]); const products=fetchItems<Products>([{id:1,name:"laptop"}]) console.log(users +"has a great"+products);
Generics in TypeScript are a powerful tool for writing flexible, reusable, and type-safe code. They allow developers to abstract logic over types, making it easier to create scalable and maintainable applications.
If you’re a developer looking to write cleaner and more robust code, TypeScript is definitely worth adding to your toolkit. Who knows? It might just become your favorite tool! 😊
Happy Coding! 🚀