TypeScript

TypeScript is a strongly-typed superset of JavaScript that compiles to plain JavaScript. It adds optional static typing, classes, and interfaces to help catch errors during development.

Why TypeScript?

  • Catch errors before runtime
  • Better IDE support and autocomplete
  • Improved code documentation
  • Easier refactoring
  • Enhanced collaboration in teams

Basic Types

typescript
// Primitives
let name: string = 'Alice'
let age: number = 30
let isActive: boolean = true

// Arrays
let numbers: number[] = [1, 2, 3]
let items: Array<string> = ['a', 'b', 'c']

// Objects
interface User {
  name: string
  age: number
  email?: string // Optional property
}

const user: User = {
  name: 'Bob',
  age: 25
}

// Functions
function add(a: number, b: number): number {
  return a + b
}

const greet = (name: string): void => {
  console.log(`Hello, ${name}`)
}

Advanced Types

typescript
// Union types
let id: string | number = 123

// Type aliases
type Status = 'pending' | 'success' | 'error'

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

// Interfaces
interface Person {
  name: string
  age: number
}

// Type assertion
const input = document.querySelector('input') as HTMLInputElement

React with TypeScript

typescript
interface Props {
  name: string
  age?: number
}

const Greeting: React.FC<Props> = ({ name, age }) => {
  return <h1>Hello, {name}</h1>
}

// Hooks with types
const [count, setCount] = useState<number>(0)
const [user, setUser] = useState<User | null>(null)

Configuration

json
// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}

Learn More