Introduction
TypeScript is an open-source programming language developed by Microsoft. It is a superset of JavaScript that adds static typing, making code more reliable, scalable, and maintainable.
Why Use TypeScript?
1. Static Typing
TypeScript enables static type checking, which helps catch errors during development rather than runtime.
2. Improved Code Readability
With explicit types, TypeScript makes the code more understandable and easier to maintain.
3. Better Developer Experience
Features like IntelliSense, auto-completion, and better error detection improve productivity.
4. Object-Oriented Programming (OOP) Support
TypeScript includes features like interfaces, generics, and access modifiers, making it ideal for large-scale applications.
5. Compatibility with JavaScript
Since TypeScript is a superset of JavaScript, existing JavaScript code can be gradually migrated to TypeScript.
Installing TypeScript
To install TypeScript globally, run:
npm install -g typescript
To check if TypeScript is installed:
tsc --version
TypeScript Basics
Variables & Types
let name: string = "John";
let age: number = 30;
let isDeveloper: boolean = true;
Functions with Type Annotations
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("Alice"));
Interfaces
Interfaces define object structure:
interface User {
id: number;
name: string;
isAdmin: boolean;
}
const user: User = { id: 1, name: "John", isAdmin: true };
Classes
class Person {
constructor(private name: string, private age: number) {}
introduce(): string {
return `My name is ${this.name} and I am ${this.age} years old.`;
}
}
const person = new Person("Alice", 25);
console.log(person.introduce());
Generics
Generics allow reusable code:
function identity
return value;
}
console.log(identity
console.log(identity
TypeScript Configuration
Create a tsconfig.json file for project configuration:
{
"compilerOptions": {
"target": "ES6",
"module": "CommonJS",
"strict": true,
"outDir": "./dist"
}
}
Compile TypeScript files using:
tsc
Conclusion
TypeScript enhances JavaScript by adding static typing, improving code quality, and enabling better tooling. Whether you're working on a small project or a large-scale application, TypeScript provides significant benefits.