|

novembre 2025

TypeScript Best Practices for React

Why TypeScript for React?

TypeScript adds static typing to React applications, catching errors at compile time rather than runtime. This leads to more maintainable code and better developer experience with enhanced IDE support.

Component Props Typing

// Define props interface
interface ButtonProps {
  variant: 'primary' | 'secondary'
  size?: 'sm' | 'md' | 'lg'
  children: React.ReactNode
  onClick?: () => void

// Use with components function Button({ variant, size = 'md', children, onClick }: ButtonProps) { return ( <button className={cn(variant, size)} onClick={onClick}> {children} </button> ) } ```

Generic Components

interface ListProps<T> {
  items: T[]
  renderItem: (item: T) => React.ReactNode

function List<T>({ items, renderItem }: ListProps<T>) { return <ul>{items.map(renderItem)}</ul> } ```

Event Handlers

// Properly typed event handlers
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  setValue(e.target.value)

const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault() // handle form submission } ```

Key Practices

  • Use interface for props, type for unions
  • Avoid any - use unknown when type is truly unknown
  • Enable strict mode in tsconfig.json
  • Use const assertions for literal types
  • Leverage utility types (Partial, Pick, Omit)