Skip to content

TypeScript for Beginners: Why You Should Learn It

TypeScript is becoming the standard for large-scale JavaScript development. Here's why you should learn it.

What is TypeScript?

TypeScript is a superset of JavaScript that adds optional static typing:

typescript
// JavaScript
function sum(a, b) {
  return a + b;
}

// TypeScript
function sum(a: number, b: number): number {
  return a + b;
}

Main Advantages

1. Type Safety

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

function getUser(id: number): User {
  // ...fetch from API
  return { id, name: 'Mario', email: 'mario@example.com' };
}

2. Better Autocompletion

IDEs can offer more accurate suggestions thanks to types.

3. Safe Refactoring

TypeScript warns you if you change a function's interface.

Installation

bash
npm install -g typescript
tsc --init

Basic Configuration (tsconfig.json)

json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "strict": true,
    "outDir": "./dist",
    "rootDir": "./src"
  }
}

Fundamental Types

typescript
// Primitive types
let name: string = 'Mario';
let age: number = 30;
let active: boolean = true;

// Arrays
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ['Mario', 'Luigi'];

// Union types
let id: string | number = 'abc';
id = 123; // OK

// Type aliases
type Point = {
  x: number;
  y: number;
};

// Interfaces
interface User {
  id: number;
  name: string;
  email?: string; // optional
}

Conclusion

TypeScript improves the developer experience and reduces runtime bugs. The learning curve is steep at first, but the benefits are enormous for projects of any size.

Made with ❤️ by PeterDev
'Ho mio cuGGGino che lo sa fare' cit.