TypeScript with React

TypeScript is JavaScript with types (labels for the kind of data), and types are checked in the editor before the code runs. Write the shape of the props…

You pass age="17" to a component that calculates age + 1, and the result is "171". The reason: "17" is text, so the plus sign joins text instead of adding. No error, just a strange number, and you only notice when someone complains. TypeScript catches mistakes like this much earlier.

TypeScript is JavaScript with types. A type is a label for the kind of data, such as text, a number or a function, and types are checked before the code runs. In React, TypeScript files end in .tsx, and the things that most often get a type are props, state and events. Imagine a registration form whose boxes are already set: "Name (text)" and "Age (number)". If you write "seventeen" in the age box, the clerk at the counter refuses it before the form is processed. In React, the form is a component, its boxes are props, and the label "(number)" is a type. TypeScript is the clerk: it refuses wrong entries in the editor, before the app runs in the browser.

Props: write their shape once

The ProfileCard component below writes the shape of its props with type. The shape of the props means which props it accepts, and the type of each one:

type ProfileCardProps = {
  name: string
  age: number
  isAdmin?: boolean // ? means it may be left out
  onGreet?: () => void // a function with no arguments that returns nothing
}

function ProfileCard({ name, age, isAdmin = false, onGreet }: ProfileCardProps) {
  return (
    <div onClick={onGreet}>
      <h2 id="name">{name}</h2>
      <p id="age">{age} years old</p>
      {isAdmin && <span>admin</span>}
    </div>
  )
}

<ProfileCard name="Budi" age={17} />

Every time the component is used, TypeScript matches the props passed in against the shape ProfileCardProps. This is what TypeScript says for four ways of using ProfileCard:

Code What TypeScript says
<ProfileCard name="Budi" age={17} /> fine, no error
<ProfileCard name="Budi" age="17" /> Type 'string' is not assignable to type 'number'. (ts 2322)
<ProfileCard name="Budi" /> Property 'age' is missing in type '{ name: string; }' but required in type 'ProfileCardProps'. (ts 2741)
<ProfileCard name="Budi" age={17} city="Manchester" /> Property 'city' does not exist on type 'IntrinsicAttributes & ProfileCardProps'. (the explanation under ts 2322)

A number like ts 2322 is the TypeScript error's number. In a code editor, the error appears as a red underline right on the code that's wrong, so you know where it is before you open the browser.

State: let it be inferred, unless it starts as null

The comment at the end of each line below gives the type that state gets:

type User = { name: string }

const [count, setCount] = useState(0) // count: number
const [user, setUser] = useState<User | null>(null) // user: User | null
const [items, setItems] = useState<string[]>([]) // items: string[]

Events: use React's own types

A handler written apart from the JSX needs a type for e, its event object:

function NameForm() {
  const [name, setName] = useState("")

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setName(e.target.value) // e.target is an <input>, so .value is sure to exist
  }

  return <input value={name} onChange={handleChange} />
}

children: React.ReactNode

The prop children holds whatever sits between the component's opening and closing tag. Its type is written like this:

type CardProps = {
  title: string
  children: React.ReactNode // text, numbers, JSX, arrays, null: anything that can render
}

React.ReactNode is the loosest type: anything that can be rendered is allowed. So <Card title="Profile"><p>Hello</p></Card> is fine.

Types are gone when it runs

Take a guess first. ProfileCard wants age to be a number, but you write <ProfileCard name="Budi" age="17" /> and run npm run dev anyway. What shows in the browser: a red error, a blank page, or "17 years old"?

The answer is "17 years old". Browsers don't understand types, so before the code runs, every type is removed. This is what's left of ProfileCard after its types are removed:

function ProfileCard({ name, age, isAdmin = false, onGreet }) {
  return (
    <div onClick={onGreet}>
      <h2 id="name">{name}</h2>
      <p id="age">{age} years old</p>
      {isAdmin && <span>admin</span>}
    </div>
  )
}

type ProfileCardProps is gone completely, and so is : ProfileCardProps. During npm run dev, Vite only removes the types without checking them. So age="17" shows normally, even though TypeScript already complained in the editor. What checks the types is the editor (the red underline) and the tsc command, the TypeScript checker. In Vite's TypeScript template, tsc runs as part of npm run build, the command that prepares the version for users ("build": "tsc -b && vite build"). So the build fails until the error is fixed. Data that arrives while the app runs, such as the result of a fetch, isn't checked by TypeScript either.

⚠️ Types that get locked, disabled, or never checked

TL;DR: TypeScript is JavaScript with types (labels for the kind of data), and types are checked in the editor before the code runs. Write the shape of the props (which props and their types) once with type (or interface): string for text, number for a number, ? for an optional prop, () => void for a function that returns nothing, React.ReactNode for children. TypeScript infers a state's type from its starting value. If the state starts as null or [], write the type yourself inside < >: useState<User | null>(null) (it holds a User or null) and useState<string[]>([]) (an array of strings). Events use React's types: React.ChangeEvent<HTMLInputElement> for onChange, React.MouseEvent<HTMLButtonElement> for onClick, React.SubmitEvent<HTMLFormElement> for onSubmit. Every type is removed before the code runs, so type errors are caught by the editor and tsc (the TypeScript checker), not the browser.

⚡ Write the props' shape once

Write:

type ProfileCardProps = {
  name: string
  age: number
  isAdmin?: boolean // ? means it may be left out
}

function ProfileCard({ name, age, isAdmin = false }: ProfileCardProps) {
  return (
    <div>
      <h2 id="name">{name}</h2>
      <p id="age">{age} years old</p>
      {isAdmin && <span>admin</span>}
    </div>
  )
}

Meaning: TypeScript adds types (labels for the kind of data) to JavaScript code, then checks them before the code runs. type ProfileCardProps = { ... } writes the shape of ProfileCard's props once: string means text, number a number, boolean true or false, and ? marks a prop that may be left out. : ProfileCardProps puts that shape on the component's props. The editor marks wrong props, such as age="17" (text, not a number).

⚡ State that starts as null

Write:

type User = { name: string }

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

Meaning: TypeScript usually infers (guesses) a state's type from its starting value, so useState(0) makes count a number. null alone isn't enough to infer from, so write the type yourself inside < >. type User = { name: string } is the shape of a user's data, and User | null means it holds a User or null.

⚡ Types are gone at run time

Guess first: you write age="17", then run npm run dev. What shows in the browser?

"17 years old", as normal. Browsers don't understand types, so Vite only removes the types without checking them.

Meaning: What checks the types is the editor (the red underline) and the tsc command, the TypeScript checker. In Vite's TypeScript template, tsc runs as part of npm run build (the command that prepares the version for users), so the build fails until the error is fixed.

What you will learn