Skip to content

JavaScript & TypeScript

Qianhe Chen edited this page Nov 9, 2024 · 1 revision

JavaScript & TypeScript

Introduction

JavaScript (JS) and TypeScript (TS) are the foundational languages of our project. While JavaScript is the standard language for web development, TypeScript adds static typing to help us write more robust and maintainable code.

JavaScript (ES6+)

What is JavaScript?

JavaScript is a dynamic programming language that powers the web. Our project uses modern JavaScript (ES6+ features) to take advantage of the latest language improvements.

Key Features We Use

  1. Arrow Functions
// Traditional function
function add(a, b) {
  return a + b;
}

// Arrow function
const add = (a, b) => a + b;
  1. Destructuring
const user = {
  name: 'John',
  age: 30
};

// Extract properties
const { name, age } = user;
  1. Spread/Rest Operators
// Spread operator
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]

// Rest parameter
const sum = (...numbers) => numbers.reduce((a, b) => a + b, 0);
  1. Async/Await
// Fetching data
async function fetchUserData() {
  try {
    const response = await fetch('/api/user');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching user:', error);
  }
}

TypeScript

What is TypeScript?

TypeScript is a superset of JavaScript that adds optional static typing. It helps catch errors early in development and provides better tooling support.

Why We Use TypeScript

  1. Type Safety

    • Catch errors during development
    • Better IDE support
    • Self-documenting code
  2. Enhanced Maintainability

    • Easier refactoring
    • Clear interfaces between components
    • Better team collaboration

Key TypeScript Features

  1. Type Annotations
// Basic types
let name: string = "John";
let age: number = 30;
let isActive: boolean = true;

// Array types
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["John", "Jane"];
  1. Interfaces
// Define a contract for objects
interface User {
  id: number;
  name: string;
  email: string;
  age?: number;  // Optional property
}

// Use the interface
const user: User = {
  id: 1,
  name: "John",
  email: "john@example.com"
};
  1. Type Aliases
// Create custom types
type Point = {
  x: number;
  y: number;
};

type ID = string | number;
  1. Generics
// Reusable components
function firstElement<T>(arr: T[]): T | undefined {
  return arr[0];
}

// Usage
const numbers = firstElement([1, 2, 3]);  // Type: number
const strings = firstElement(["a", "b"]); // Type: string

Project Configuration

TypeScript Configuration (tsconfig.json)

{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["src"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

Best Practices

  1. Always Use TypeScript for New Files

    • Create new files with .ts or .tsx extension
    • Define proper types for all variables and functions
  2. Type Inference

    • Let TypeScript infer types when obvious
    • Explicitly define types for function parameters and returns
  3. Null Checking

// Use optional chaining
const userName = user?.profile?.name;

// Use nullish coalescing
const displayName = userName ?? "Anonymous";
  1. Async Code
// Always properly type async functions
async function fetchData(): Promise<User[]> {
  const response = await fetch('/api/users');
  return response.json();
}

Common Pitfalls to Avoid

  1. Type Assertions

    • Avoid using as unless absolutely necessary
    • Use type guards instead when possible
  2. any Type

    • Minimize use of any
    • Use unknown for truly unknown types
  3. Type Safety

// Bad
const data: any = fetchData();

// Good
interface ApiResponse {
  users: User[];
  total: number;
}
const data: Promise<ApiResponse> = fetchData();

Further Learning

Clone this wiki locally