Cheatsheet for Typescript for React
few minutes
typescriptreact
cheatsheettypescript
Beginner
developer

1. Basic Type Syntax

let name: string = 'John'
let age: number = 30
let isAdmin: boolean = false

let tags: string[] = ['react', 'ts']

let tuple: [string, number] = ['id', 1]

let anything: any = 'avoid this'

let unknownValue: unknown

let nullable: string | null = null

2. Typing React Props

Basic Props

type ButtonProps = {
  label: string
  disabled?: boolean
}

function Button({ label, disabled }: ButtonProps) {
  return <button disabled={disabled}>{label}</button>
}

Props with Children

type CardProps = {
  title: string
  children: React.ReactNode
}

function Card({ title, children }: CardProps) {
  return (
    <div>
      <h2>{title}</h2>
      {children}
    </div>
  )
}

Function Props

type Props = {
  onClick: () => void
  onChange: (value: string) => void
}

Optional Props

type Props = {
  name?: string
}

Union Types in Props

type Props = {
  status: 'loading' | 'success' | 'error'
}

3. Typing useState

Primitive State

const [count, setCount] = useState<number>(0)

const [name, setName] = useState<string>('')

Nullable State

const [user, setUser] = useState<User | null>(null)

Array State

const [items, setItems] = useState<string[]>([])

Object State

type User = {
  id: number
  name: string
}

const [user, setUser] = useState<User>({
  id: 1,
  name: 'John',
})

Empty Object Initial State

const [user, setUser] = useState<User | null>(null)

Avoid:

useState({})

4. Typing useRef

DOM Element Ref

const inputRef = useRef<HTMLInputElement>(null)

Mutable Value Ref

const timerRef = useRef<number | null>(null)

5. Typing Events

Input Change Event

function handleChange(e: React.ChangeEvent<HTMLInputElement>) {
  console.log(e.target.value)
}

Button Click Event

function handleClick(e: React.MouseEvent<HTMLButtonElement>) {
  console.log('clicked')
}

Form Submit Event

function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
  e.preventDefault()
}

6. Typing useEffect Cleanup

useEffect(() => {
  const timer = setInterval(() => {}, 1000)

  return () => clearInterval(timer)
}, [])

No special typing usually needed.


7. Typing Context API

Create Context

type AuthContextType = {
  user: string | null
  login: () => void
}

const AuthContext = createContext<AuthContextType | null>(null)

Using Context

const auth = useContext(AuthContext)

if (!auth) {
  throw new Error('AuthContext missing')
}

8. Typing useReducer

State + Action Types

type State = {
  count: number
}

type Action = { type: 'increment' } | { type: 'decrement' }

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 }

    case 'decrement':
      return { count: state.count - 1 }

    default:
      return state
  }
}

9. Typing Async Functions

async function fetchUsers(): Promise<User[]> {
  const res = await fetch('/api/users')
  return res.json()
}

10. Typing API Responses

type ApiResponse<T> = {
  data: T
  error: string | null
}

type User = {
  id: number
  name: string
}

const response: ApiResponse<User[]> = {
  data: [],
  error: null,
}

11. Generics in React Components

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

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

12. Utility Types

Partial

Makes all fields optional.

type User = {
  id: number
  name: string
}

type PartialUser = Partial<User>

Pick

Select specific fields.

type UserPreview = Pick<User, 'id' | 'name'>

Omit

Remove fields.

type UserWithoutId = Omit<User, 'id'>

Record

Dictionary type.

const users: Record<string, number> = {
  john: 1,
  jane: 2,
}

13. Component Return Types

Usually inferred automatically.

Optional explicit typing:

function App(): JSX.Element {
  return <div>Hello</div>
}

14. Typing Custom Hooks

function useCounter(initial: number) {
  const [count, setCount] = useState(initial)

  const increment = () => setCount((c) => c + 1)

  return { count, increment }
}

Usually inference is enough.


15. Type vs Interface

Type

type User = {
  id: number
}

Interface

interface User {
  id: number
}

Common Guideline

  • type → unions, utility composition
  • interface → extendable object contracts

Modern React code commonly prefers type.


16. Common React + TS Patterns

Destructured Props

type Props = {
  title: string
}

function Header({ title }: Props) {
  return <h1>{title}</h1>
}

Inline Type

function Header({ title }: { title: string }) {
  return <h1>{title}</h1>
}

Good for very small components only.


Default Values

type Props = {
  size?: number
}

function Avatar({ size = 100 }: Props) {
  return <div>{size}</div>
}

17. Useful React Types

React.ReactNode
React.ReactElement
React.FC
React.Dispatch
React.SetStateAction

18. Avoid These

Avoid any

const data: any

Prefer:

const data: unknown

Avoid Overusing React.FC

Usually unnecessary.

Prefer:

function Button() {}

Instead of:

const Button: React.FC = () => {}

Avoid Type Assertions Unless Necessary

Avoid:

const input = document.getElementById('x') as HTMLInputElement

19. Fast Mental Model

Props

type Props = {}

State

useState<Type>()

Event

React.ChangeEvent<HTMLInputElement>

Ref

useRef<HTMLInputElement>(null)

Async

Promise<Type>

20. Most Important Types to Memorize

string
number
boolean

Type | null
Type[]

React.ReactNode

React.ChangeEvent<HTMLInputElement>

React.MouseEvent<HTMLButtonElement>

useState<Type>()

useRef<Type>(null)

Promise<Type>