Important concepts with examples:

Let's dive into each of these important TypeScript concepts with code examples:

Absolutely! Let's dive into each of these important TypeScript concepts with code examples:

1. Type Annotations & Declarations

let age: number;
let name: string;

age = 25;
name = 'John';

// Custom Types
type Point = {
  x: number;
  y: number;
};

interface User {
  id: number;
  username: string;
  email: string;
}

let point: Point = { x: 10, y: 20 };
let user: User = { id: 1, username: 'johndoe', email: '[email protected]' };

2. Functions

// Arrow Functions
const add = (a: number, b: number): number => a + b;

// Optional & Default Parameters
const greet = (name: string, greeting: string = 'Hello') => `${greeting}, ${name}!`;

// Rest Parameters
const sumAll = (...numbers: number[]): number => numbers.reduce((acc, val) => acc + val, 0);

3. Interfaces & Types

// Interfaces
interface Shape {
  color: string;
  area(): number;
}

// Type Aliases
type Greeting = string;
type UserID = string | number;

4. Generics

// Function with Generics
function identity<T>(arg: T): T {
  return arg;
}

let output = identity<string>('Hello');
// TypeScript infers output to be of type 'string'

5. Classes & Inheritance

// Class Inheritance
class Animal {
  constructor(public name: string) {}

  move(distance: number = 0) {
    console.log(`${this.name} moved ${distance}m.`);
  }
}

class Dog extends Animal {
  bark() {
    console.log('Woof! Woof!');
  }
}

const dog = new Dog('Rex');
dog.move(10);
dog.bark();

6. Modules & Namespaces

// Modules
// File: math.ts
export function sum(a: number, b: number): number {
  return a + b;
}

// File: app.ts
import { sum } from './math';
console.log(sum(5, 3)); // Outputs: 8

7. Enums

// Enums
enum Direction {
  Up = 'UP',
  Down = 'DOWN',
  Left = 'LEFT',
  Right = 'RIGHT',
}

let playerDirection: Direction = Direction.Up;

8. Type Assertion & Casting

// Type Assertion
let someValue: any = 'hello';
let strLength: number = (someValue as string).length;

// Type Casting
let userInput: unknown;
let userName: string = (userInput as string).toUpperCase();

9. Asynchronous Programming

// Promises & async/await
function delay(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function asyncFunction() {
  console.log('Before delay');
  await delay(2000);
  console.log('After delay');
}

10. TypeScript Compiler (tsc)

// tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules"]
}

11. Advanced TypeScript Features

// Intersection & Union Types
type Admin = {
  id: string;
  role: 'admin';
};

type User = {
  id: string;
  role: 'user';
};

type AdminUser = Admin & User; // Intersection
type UserRole = 'admin' | 'user'; // Union

Each of these examples demonstrates the basic usage of these TypeScript concepts. Experimenting with these examples and applying them in your projects will deepen your understanding of TypeScript's capabilities and how to leverage them effectively.

Last updated