Sub topic 9
Describing Props with TypeScript
Props are the public interface of a component. In plain JavaScript, nothing stops a caller from passing a number where a string is expected, or from leaving out a required prop. TypeScript moves those mistakes from runtime to the editor and the build.
This chapter assumes you know the following:
- Basic TypeScript syntax: type annotations, unions, and optional properties.
- Function components, props destructuring, and callback props, which earlier chapters cover.
- A project that compiles
.tsxfiles, for example a Vite React TypeScript template.
Typing a props object
A component receives one argument, the props object. You describe its shape with a type alias or an interface and annotate the destructured parameter with it.
type ButtonProps = {
label: string;
variant?: 'primary' | 'secondary';
onClick: () => void;
};
function Button({ label, variant = 'primary', onClick }: ButtonProps) {
return (
<button className={variant} onClick={onClick}>
{label}
</button>
);
}Each line of ButtonProps states a rule:
label: stringis required and must be a string.variant?:is optional. Inside the component its type is'primary' | 'secondary' | undefined. The default value in the destructuring removes theundefinedcase, sovariantis always one of the two strings in the function body.onClick: () => voidis a required function that takes no arguments. The return typevoidmeans the component ignores whatever the function returns.
The compiler checks every use of Button:
<Button label="Save" onClick={() => console.log('saved')} /> // OK
<Button label="Save" /> // Error: onClick is missing
<Button label={42} onClick={() => {}} /> // Error: number is not string
<Button label="Save" variant="danger" onClick={() => {}} /> // Error: "danger" is not allowedThe last error shows why union types are useful for props. A set of allowed strings works like an enum, and your editor can autocomplete the values.
Type alias or interface
Both work for props. The practical differences are small.
| Feature | `type` | `interface` | Column |
|---|---|---|---|
| Object shapes | Yes | Yes | |
| Unions such as `A \ | B` | Yes | No |
| Extending another shape | Intersection with `&` | `extends` | |
| Declaration merging (same name declared twice) | No | Yes |
Pick one and use it consistently. A common rule is to use type for props because you will eventually need a union, and interface only when a library's conventions ask for it.
Optional props and default values
Marking a prop optional with ? only changes the type. It does not supply a value. The default comes from the destructuring pattern, as in variant = 'primary' above.
Two points cause trouble in practice:
- A default applies only when the value is
undefined. Passingnullor0does not trigger it. - If you do not destructure,
props.variantstays possiblyundefinedin the body, and you must handle that yourself.
Typing different kinds of values
Props can hold any JavaScript value. These are the types you will write most often.
type User = { id: number; name: string };
type UserListProps = {
users: User[];
selectedId: number | null;
onSelect: (id: number) => void;
renderBadge?: (user: User) => React.ReactNode;
style?: React.CSSProperties;
};
function UserList({ users, selectedId, onSelect, renderBadge, style }: UserListProps) {
return (
<ul style={style}>
{users.map((user) => (
<li
key={user.id}
aria-current={user.id === selectedId}
onClick={() => onSelect(user.id)}
>
{user.name}
{renderBadge?.(user)}
</li>
))}
</ul>
);
}Notes on this example:
selectedId: number | nullmakes "nothing selected" an explicit, required decision. The caller must passnullrather than forgetting the prop.onSelect: (id: number) => voiddescribes the arguments the child will pass up. The parent's handler is checked against this signature.renderBadge?.(user)uses optional chaining, because the prop may be missing.React.ReactNodeis the type for anything React can render: strings, numbers, elements, arrays,null, andundefined.React.CSSPropertiesis the type of thestyleprop on DOM elements.
Typing children
children is an ordinary prop, so you declare it yourself. Use React.ReactNode unless you need something stricter.
import type { ReactNode } from 'react';
type CardProps = {
title: string;
children: ReactNode;
};
function Card({ title, children }: CardProps) {
return (
<section className="card">
<h2>{title}</h2>
{children}
</section>
);
}Choose the type by how the component uses the prop:
| Type | Accepts | Use when |
|---|---|---|
| `ReactNode` | Anything renderable | Wrapper components that just place content |
| `ReactElement` | A single JSX element only | You need to inspect or clone the element |
| `string` | Text only | Labels where nested markup is not allowed |
| `(value: T) => ReactNode` | A render function | Render props |
Declaring children: ReactNode makes the prop required. Write children?: ReactNode when the component can be used without content.
Slot props follow the same rule. A prop such as header: ReactNode accepts <h1>Dashboard</h1>, and sidebar?: ReactNode makes the slot optional.
Extending native element props
Wrapper components often forward attributes to a DOM element. Rather than listing every attribute, borrow the types React already defines.
import type { ComponentPropsWithoutRef } from 'react';
type TextInputProps = ComponentPropsWithoutRef<'input'> & {
label: string;
};
function TextInput({ label, ...rest }: TextInputProps) {
return (
<label>
{label}
<input {...rest} />
</label>
);
}
function Example() {
return <TextInput label="Email" type="email" placeholder="[email protected]" required />;
}ComponentPropsWithoutRef<'input'> contains every attribute valid on an <input>, such as type, placeholder, required, and onChange, each with the correct type. The intersection & adds your own label. The rest pattern then forwards everything else, and the compiler confirms that the forwarded props fit the element.
If a native prop has the same name as one of yours with a different type, the intersection can produce never for that property. Use Omit to remove the clashing key first:
import type { ComponentPropsWithoutRef } from 'react';
type SizedInputProps = Omit<ComponentPropsWithoutRef<'input'>, 'size'> & {
size: 'sm' | 'lg';
};The native size attribute is a number, so the example removes it before declaring a string union under the same name.
Typing event handlers
When a prop receives an event handler, use React's event types. They carry the right target and currentTarget types.
import type { ChangeEvent } from 'react';
type SearchBoxProps = {
value: string;
onChange: (value: string) => void;
};
function SearchBox({ value, onChange }: SearchBoxProps) {
function handleChange(event: ChangeEvent<HTMLInputElement>) {
onChange(event.target.value);
}
return <input value={value} onChange={handleChange} />;
}This design is deliberate. The component handles the DOM event internally and exposes a simple (value: string) => void to its parent. The parent never needs to know about ChangeEvent. When you instead want to forward the raw event, type the prop as React.ChangeEventHandler<HTMLInputElement>.
Discriminated unions for related props
Sometimes props only make sense in combinations. Two independent optional props allow invalid pairings. A discriminated union rules them out.
type AlertProps =
| { status: 'info'; message: string }
| { status: 'error'; message: string; onRetry: () => void };
function Alert(props: AlertProps) {
if (props.status === 'error') {
return (
<div role="alert">
{props.message}
<button onClick={props.onRetry}>Retry</button>
</div>
);
}
return <p>{props.message}</p>;
}Here status is the discriminant. Inside the if, TypeScript narrows props to the error variant, so props.onRetry is known to exist. Passing status="info" together with onRetry is a compile error.
Notice that this component does not destructure in the parameter list. Destructuring separates the discriminant from the other props, and narrowing then works less predictably in older TypeScript versions. Keep props whole until you have narrowed it.
Generic components
A component that works with a list of any item type can take a type parameter, so the callbacks stay type-safe.
import type { ReactNode } from 'react';
type ListProps<T> = {
items: T[];
getKey: (item: T) => string | number;
renderItem: (item: T) => ReactNode;
};
function List<T>({ items, getKey, renderItem }: ListProps<T>) {
return (
<ul>
{items.map((item) => (
<li key={getKey(item)}>{renderItem(item)}</li>
))}
</ul>
);
}
function Example() {
const names = [{ id: 1, name: 'Ada' }, { id: 2, name: 'Grace' }];
return (
<List
items={names}
getKey={(n) => n.id}
renderItem={(n) => <strong>{n.name}</strong>}
/>
);
}TypeScript infers T from items, so n in both callbacks is typed as { id: number; name: string } without any annotation.
Common mistakes
- Using
React.FCby habit. It is legal, but it adds little. A plain function with an annotated parameter is simpler, supports generics cleanly, and is the current community default. - Typing props as
anyorobject. This turns off the checks you wanted. Useunknownwhen the shape is truly unknown, then narrow. - Marking everything optional. Optional props push
undefinedchecks into the component. Make a prop required unless a missing value has a sensible meaning. - Treating types as runtime validation. Types are erased at build time. Data from a network request or
JSON.parseis not checked by your prop types. Validate it at the boundary, for example with a schema library. - Inline object types repeated across files. Name the type once and export it so parents and tests can reuse it.
Exercise
A Badge component has type BadgeProps = { count: number; max?: number }. Its body reads props.max directly without destructuring or a default. What type does props.max have there, and how would you make the body treat it as a plain number with a default of 99?
Show answer
Without destructuring, props.max has type number | undefined. Destructure with a default in the parameter list, function Badge({ count, max = 99 }: BadgeProps). After that, max is typed as number in the body, because the default replaces undefined.
Exercise
You are writing a Modal that must receive onClose when dismissible is true, and must not receive onClose when dismissible is false. Which TypeScript feature enforces this, and how would you write the props type?
Show answer
A discriminated union. For example: type ModalProps = { dismissible: true; onClose: () => void } | { dismissible: false }. The dismissible field is the discriminant. The compiler then rejects dismissible: true without onClose, and it narrows props inside the component when you check props.dismissible.
Exercise
A Link component spreads ...rest onto an <a> element. Which type should LinkProps extend so that href, target, and onClick are all accepted and correctly typed, and why might you need Omit?
Show answer
Use ComponentPropsWithoutRef<'a'> and intersect it with your own props: type LinkProps = ComponentPropsWithoutRef<'a'> & { external?: boolean }. You need Omit if one of your prop names clashes with a native attribute and has a different type, because the intersection would otherwise make that property unusable.