Skip to main content

TypeScript Configuration

This document details the TypeScript configuration for the STO Education Platform project.

Configuration Files

tsconfig.json

Main TypeScript configuration file that extends specific configurations:
{
  "files": [],
  "references": [
    {
      "path": "./tsconfig.app.json"
    },
    {
      "path": "./tsconfig.node.json"
    }
  ]
}
Purpose: Uses project references to separate application and build tool configurations.

tsconfig.app.json

Configuration for the main application code:
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "isolatedModules": true,
    "moduleDetection": "force",
    "noEmit": true,
    "jsx": "react-jsx",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["src"]
}
Key Settings:
  • target: ES2020 for modern JavaScript features
  • jsx: react-jsx for React 17+ JSX transform
  • strict: Enables all strict type checking options
  • noEmit: TypeScript only checks types, doesn’t emit JavaScript
  • baseUrl/paths: Path mapping for cleaner imports (@/./src/)

tsconfig.node.json

Configuration for Node.js build tools and scripts:
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["ES2023"],
    "module": "ESNext",
    "skipLibCheck": true,
    "moduleResolution": "bundler",
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "moduleDetection": "force",
    "noEmit": true,
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["vite.config.ts"]
}
Purpose: Separate configuration for build tools with different requirements than the main app.

Type Safety Features

Strict Mode Enabled

The configuration enables strict TypeScript checking:
  • noImplicitAny: Prevents implicit any types
  • strictNullChecks: Ensures null/undefined safety
  • strictFunctionTypes: Strict checking of function parameter types
  • noImplicitReturns: All code paths must return a value
  • noFallthroughCasesInSwitch: Prevents fallthrough in switch statements

Path Mapping

Clean import paths using @/ prefix:
// Instead of:
import { supabase } from '../../../lib/supabase'

// Use:
import { supabase } from '@/lib/supabase'

Type Definitions

Built-in Types

The project includes comprehensive type definitions in /src/types/:
  • index.ts: Core interfaces and types
  • BlogPost.ts: Blog-related types
  • Session.ts: Session management types
  • User.ts: User and profile types
  • Course.ts: Course and education types
  • Payment.ts: Payment processing types

Third-Party Types

Type definitions for external libraries:
// Supabase types
import { Database } from '@/types/database'

// React types
import { ReactNode, ComponentType } from 'react'

// Router types
import { NavigateFunction, Location } from 'react-router-dom'

Build Integration

Vite Integration

TypeScript works seamlessly with Vite:
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()], // Handles TypeScript compilation
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
})

Development Experience

Features:
  • Real-time type checking in IDE
  • Auto-completion and IntelliSense
  • Error highlighting and diagnostics
  • Refactoring support
  • Import/export validation
IDE Support:
  • VS Code with TypeScript extension
  • WebStorm/IntelliJ IDEA
  • Vim/Neovim with LSP

Type Checking in CI/CD

Type checking is integrated into the build process:
{
  "scripts": {
    "build": "tsc && vite build",
    "type-check": "tsc --noEmit"
  }
}
Benefits:
  • Catches type errors before deployment
  • Ensures type safety across the codebase
  • Prevents runtime type-related bugs

Best Practices

Type Definitions

  1. Use Interfaces for Objects:
interface User {
  id: string
  email: string
  role: 'student' | 'teacher' | 'admin'
}
  1. Use Types for Unions:
type Status = 'pending' | 'approved' | 'rejected'
  1. Generic Types for Reusability:
interface ApiResponse<T> {
  data: T
  success: boolean
  message?: string
}

Import/Export Types

// Export types explicitly
export type { User, Course, Session }

// Import types with type keyword
import type { User } from '@/types'

Strict Type Checking

  1. Avoid any Type:
// Bad
const data: any = response.data

// Good
const data: ApiResponse<User> = response.data
  1. Use Type Guards:
function isUser(obj: unknown): obj is User {
  return typeof obj === 'object' && obj !== null && 'id' in obj
}

Common Patterns

API Response Types

interface ApiResponse<T> {
  data: T
  success: boolean
  error?: string
}

interface PaginatedResponse<T> extends ApiResponse<T[]> {
  pagination: {
    page: number
    limit: number
    total: number
    hasMore: boolean
  }
}

Component Props Types

interface ButtonProps {
  children: ReactNode
  variant?: 'primary' | 'secondary'
  size?: 'sm' | 'md' | 'lg'
  disabled?: boolean
  onClick?: () => void
}

const Button: React.FC<ButtonProps> = ({ children, ...props }) => {
  // Component implementation
}

Hook Return Types

interface UseApiResult<T> {
  data: T | null
  loading: boolean
  error: string | null
  refetch: () => Promise<void>
}

function useApi<T>(url: string): UseApiResult<T> {
  // Hook implementation
}

Troubleshooting

Common Issues

  1. Module Resolution Errors:
    • Ensure baseUrl and paths are correctly configured
    • Check import paths match the path mapping
  2. Type Import Errors:
    • Use import type for type-only imports
    • Ensure types are properly exported
  3. Strict Mode Errors:
    • Add explicit types instead of relying on inference
    • Use type assertions when necessary
    • Handle null/undefined cases explicitly

Performance Optimization

  1. Skip Lib Check: Enabled to speed up compilation
  2. Incremental Compilation: TypeScript caches compilation results
  3. Project References: Separate configurations for different parts