Why choose typescript over javascript?
Are you a web developer or a web enthusiast who is using React.js, Vue.js, or Next.js for building web apps? If yes, then you should definitely check out TypeScript. In this blog, I will mostly talk about the difference between typescript and javascript and why you should prefer .ts (.tsx) over .js (.jsx).
Javascript
JavaScript is a versatile, high-level programming language primarily used for web development. It empowers browsers to dynamically update content, enhance user interactions, and create responsive interfaces. Its event-driven paradigm and ability to manipulate Document Object Model (DOM) elements make it a crucial tool for building interactive and engaging websites.
You can guarantee that JavaScript is used whenever a web page does anything more than just sit there and show you static data. Examples of such features include interactive maps, dynamic 2D and 3D visuals, scrolling video jukeboxes, and timely content updates. It is the third layer in the stack of common web technologies, the first two of which are HTML and CSS.
In the ever-evolving landscape of web development, the choice between TypeScript and JavaScript is a crucial decision that can significantly impact the quality and maintainability of your code. While both languages serve as the backbone of modern web applications, TypeScript emerges as a powerful contender, offering a plethora of advantages that go beyond the capabilities of its predecessor, JavaScript.
Typescript
TypeScript is a superset of JavaScript, introducing static typing to enhance code reliability and maintainability. Developed by Microsoft, it compiles to plain JavaScript and supports the latest ECMAScript features. TypeScript introduces interfaces, classes, and other object-oriented programming concepts, enabling developers to define and enforce clear data structures. Its static typing helps catch potential errors during development, leading to more robust applications. With a strong tooling ecosystem and wide industry adoption, TypeScript facilitates scalable and maintainable codebases, making it an excellent choice for large-scale web and server-side development projects, where type safety and code organization are crucial considerations.
Several Big Tech Companies like Google, Microsoft, Meta, Netflix, Airbnb have add Typescript to their tech stacks. TypeScript is used in all major applications which we usually use in our daily life such as Gmail, Google Search, Youtube, Visual Studio Code ( for developers), Office 365, Facebook, Instagram, etc.
Advantages of using TypeScript over JavaScript
Static Typing
Static Typing requires developers to explicitly specify variable types. Take the variable “num” in TypeScript, for instance. The code won’t execute without assigning a type, like Integer, Float, List, or another. TypeScript enforces static typing, offering benefits like early bug detection and quicker code completion.
// JavaScript (No Static Typing)
let str = "Hello, World!";
console.log(str);
// Attempting to assign a different type later is allowed
str = 42;
console.log(str); // This would execute without error in JS
// TypeScript (Static Typing)
let str: string = "Hello, World!";
console.log(str);
// Attempting to assign a different type results in a compile-time error
// Uncommenting the line below would result in a TypeScript compilation error
// str = 42;
// console.log(str);
Interchangeable
TypeScript is an extension of JavaScript, allowing seamless integration of JavaScript code and libraries. All legitimate TypeScript code is equivalent to valid JavaScript code. A JavaScript file saved in TypeScript with a.ts extension runs without any problems. TypeScript and JavaScript are essentially equivalent, thus you can progressively integrate TypeScript into an existing JavaScript codebase. All that’s required to convert a JavaScript file to TypeScript is to add types to each module. Although every line of JavaScript is also TypeScript, it’s important to remember that TypeScript has extra features for better development, such as static typing.
Typecasting
The reason to use TypeScript over JavaScript is that it also allows TypeCasting. It indicates the problem while writing, making it simple and quick to answer the inquiry. It also becomes simple to transform a variable from one type to another with TypeCasting. You may instantly modify a variable’s type with TypeCasting to suit your needs. For type castings, the <> operator or the “as” keyword work well. Additionally, it provides you with tips when you run into trouble creating code, making it simpler. The compilation error is shown by TypeScript during development.
// TypeScript example demonstrating Type Casting
// Example 1: Using "as" keyword
let stringValue: any = "42";
let numberValue1: number = stringValue as number;
console.log(Using "as" keyword: ${numberValue1}
);
// Example 2: Using < > operator
let anotherStringValue: any = "77";
let numberValue2: number = <number>anotherStringValue;
console.log(Using < > operator: ${numberValue2}
);
Interface Support
Unlike JavaScript, TypeScript allows types to be defined using interfaces. An interface specifies the methods and attributes that an object must have, but it does not actually implement them. This language construct is very useful when working with other developers.
The example shows how to use TypeScript’s capabilities to implement standard Object Oriented Progarmming patterns —
// Define an interface for a BankAccount
interface BankAccount {
accountNumber: string;
balance: number;
deposit(amount: number): void;
withdraw(amount: number): void;
}
// Implement a class for SavingsAccount that implements BankAccount
class SavingsAccount implements BankAccount {
constructor(public accountNumber: string, public balance: number) {}
deposit(amount: number): void {
this.balance += amount;
console.log(Deposited ${amount}. New balance: ${this.balance}
);
}
withdraw(amount: number): void {
if (amount <= this.balance) {
this.balance -= amount;
console.log(Withdrawn ${amount}. New balance: ${this.balance}
);
} else {
console.log("Insufficient funds!");
}
}
}
// Implement a class for CurrentAccount that implements BankAccount
class CurrentAccount implements BankAccount {
constructor(public accountNumber: string, public balance: number) {}
deposit(amount: number): void {
this.balance += amount;
console.log(Deposited ${amount}. New balance: ${this.balance}
);
}
withdraw(amount: number): void {
// Current accounts allow overdraft up to a certain limit
const overdraftLimit = 1000;
if (amount <= this.balance + overdraftLimit) {
this.balance -= amount;
console.log(Withdrawn ${amount}. New balance: ${this.balance}
);
} else {
console.log("Exceeds overdraft limit!");
}
}
}
// Example usage
const savingsAccount = new SavingsAccount("SA123", 1000);
savingsAccount.deposit(500);
savingsAccount.withdraw(200);
const currentAccount = new CurrentAccount("CA456", 2000);
currentAccount.deposit(1000);
currentAccount.withdraw(2500);
Conclusion
In conclusion, TypeScript stands out as a powerful superset of JavaScript, offering static typing and other features that enhance the development experience. Its capacity to detect errors early, improve code maintainability, and support modern ECMAScript features makes it a valuable tool for developers. The seamless interoperability with existing JavaScript codebases facilitates a smooth transition and adoption process. However, the choice between TypeScript and JavaScript ultimately depends on the specific needs and preferences of the development team and the company’s goals. The decision to embrace TypeScript or stick with JavaScript reflects the flexibility within the development landscape, allowing companies to choose the approach that best aligns with their project requirements and development philosophies.
Guys, if you enjoyed this, please give it a clap and share it with your friends who are about to begin learning web or android development. And if you want more articles like this, follow me on Medium.
Top comments (0)