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} />
type ProfileCardProps = { ... }gives the shape of the props a name.stringmeans text,numbera number,booleantrue or false.- The
?inisAdmin?makes that prop optional (it may be left out). Without?, the prop must be passed. () => voidis the type of a function with no arguments.voidmeans the function returns nothing. This type suits an event handler such asonGreet.: ProfileCardPropsafter the destructuring braces tells TypeScript the shape of the props this component accepts.- The shape of the props can also be written with
interface:interface ProfileCardProps { name: string; age: number }. For props,typeandinterfaceboth work. Pick one and use it consistently.
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[]
useState(0): TypeScript guesses (the term is infers) the type from the starting value, so the type ofcountisnumber.setCount("1")is refused withArgument of type 'string' is not assignable to parameter of type 'SetStateAction<number>'.useState<User | null>(null): you write the type inside< >yourself, because a starting value ofnullisn't enough to infer from.|means "or": it holds aUserornull. Without<User | null>, the type is justnull, andsetUser({ name: "Budi" })is refused.useState<string[]>([]): an empty array isn't enough either.string[]means an array of strings. Without<string[]>, the type isnever[], an array that may hold nothing at all. SosetItems(["a"])is refused withType 'string' is not assignable to type 'never'.
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} />
}
onChangeon an<input>usesReact.ChangeEvent<HTMLInputElement>. What's inside< >is the element that fires the event.onClickon a<button>usesReact.MouseEvent<HTMLButtonElement>.onSubmiton a<form>usesReact.SubmitEvent<HTMLFormElement>. Older code writesReact.FormEvent<HTMLFormElement>. Since@types/react19.2 (the package that holds React's types), that type is marked deprecated (outdated), but it still works.- A handler written directly in the JSX, such as
onChange={(e) => setName(e.target.value)}, needs no type. TypeScript infers the type ofefrom where it sits: theonChangeof an<input>.
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
useState(null)without a type. The type gets locked tonull, and everysetUser(...)with an object is refused. WriteuseState<User | null>(null).anyeverywhere.anymeans "any type at all".(e: any)disables the checking, so a typo likee.target.valeuisn't marked by the editor, and you only find it in the browser.- The wrong event type. If
React.MouseEvent<HTMLButtonElement>is put on an input'sonChange, TypeScript refuses it withType '(e: React.MouseEvent<HTMLButtonElement>) => void' is not assignable to type 'ChangeEventHandler<HTMLInputElement, HTMLInputElement>'. - Expecting the exercise preview to check types. The editor in the exercise removes the types the way Vite does during
npm run dev, without checking them. Soage="17"still shows in the preview. What refuses it is the red underline in a code editor, andtsc.
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.