Sub topic 2
Typing props with interfaces and type aliases
Props are the inputs of a component. When you type them, the compiler checks every place the component is used. This chapter covers how to describe props with interface and type, which one to pick, and which mistakes the compiler catches or misses.
Prerequisites
This chapter assumes you know:
- Basic React: function components, props, and JSX.
- TypeScript basics: interfaces, type aliases, unions, and generics.
- How to run a project with strict mode on, as set up in the previous chapter. Examples assume
"strict": trueand"jsx": "react-jsx".
What a props type does
A function component receives one argument, the props object. You annotate that argument with an object type. TypeScript then checks three things:
- Every required property is passed.
- Each value has the right type.
- No unknown property is passed.
interface UserBadgeProps {
name: string;
age: number;
isAdmin: boolean;
}
export function UserBadge({ name, age, isAdmin }: UserBadgeProps) {
return (
<span>
{name} ({age}){isAdmin ? " admin" : ""}
</span>
);
}
export function Example() {
return (
<div>
<UserBadge name="Ada" age={36} isAdmin={false} />
{/* Error: Property 'isAdmin' is missing */}
{/* <UserBadge name="Grace" age={45} /> */}
{/* Error: Type 'string' is not assignable to type 'number' */}
{/* <UserBadge name="Alan" age="41" isAdmin /> */}
</div>
);
}The annotation goes on the whole parameter, after the destructuring pattern. Writing { name: string } inside the pattern does not work. In a destructuring pattern, name: string renames the property to a local variable called string.
Interface or type alias
Both describe the same object shape for props. The same component can be written either way:
type UserBadgeProps = {
name: string;
age: number;
isAdmin: boolean;
};The differences matter only at the edges.
| Feature | `interface` | `type` alias | Column |
|---|---|---|---|
| Object shapes | Yes | Yes | |
| Unions such as `A \ | B` | No | Yes |
| Extending | `extends` | Intersection with `&` | |
| Declaration merging (same name declared twice) | Yes, the declarations merge | No, a duplicate name is an error | |
| Mapped and conditional types | No | Yes | |
| Error messages for conflicts | Reported at the `extends` line | Reported where the intersection is used |
For props, a practical rule is this:
- Use
interfacefor plain object props that other types may extend. - Use
typewhen the props are a union, such as the discriminated unions covered later in this tutorial, or when you build them from other types withPick,Omit, or mapped types. - Pick one default per codebase and keep it. Consistency matters more than the choice.
Naming and placing props types
Name the type <Component>Props and keep it next to the component. Export it only when other files need it, for example a wrapper that reuses the props.
export interface TagListProps {
tags: readonly string[];
onSelect: (tag: string) => void;
}
export function TagList({ tags, onSelect }: TagListProps) {
return (
<ul>
{tags.map((tag) => (
<li key={tag}>
<button type="button" onClick={() => onSelect(tag)}>
{tag}
</button>
</li>
))}
</ul>
);
}Two details in this example are worth copying:
readonly string[]accepts both mutable and readonly arrays, and it stops the component from callingpushon an array it does not own. A plainstring[]would reject a readonly array passed by the parent.onSelectis a function type with named parameters. Parameter names in function types are documentation only, but they appear in editor tooltips.
Typing callback props
A callback prop is a property whose type is a function. Choose the return type with care.
interface SearchBoxProps {
onSearch: (query: string) => void;
onValidate: (query: string) => boolean;
}A parent may pass a function that returns a value to a prop typed => void. TypeScript allows this because the caller ignores the return value. This is why onSearch={(q) => setQuery(q)} compiles even when setQuery returns something. Use void for "I do not use the result" and a concrete type when the component reads the result.
There are two syntaxes for function-typed properties:
interface Handlers {
// property syntax: checked strictly under strictFunctionTypes
onSave: (id: number) => void;
// method syntax: parameters are checked more loosely (bivariantly)
onLoad(id: number): void;
}Prefer property syntax for callback props. Under strict, TypeScript checks the parameters of property-style functions contravariantly. A handler that wrongly accepts a narrower parameter type is rejected. Method syntax is exempt from that check, so it hides some mistakes.
Extending and combining props
Props often build on one another. With interfaces you use extends. With type aliases you use &.
interface BaseFieldProps {
label: string;
id: string;
}
interface TextFieldProps extends BaseFieldProps {
value: string;
onChange: (value: string) => void;
}
type NumberFieldProps = BaseFieldProps & {
value: number;
onChange: (value: number) => void;
};
export function TextField({ label, id, value, onChange }: TextFieldProps) {
return (
<label htmlFor={id}>
{label}
<input id={id} value={value} onChange={(e) => onChange(e.target.value)} />
</label>
);
}
export function NumberField({ label, id, value, onChange }: NumberFieldProps) {
return (
<label htmlFor={id}>
{label}
<input
id={id}
type="number"
value={value}
onChange={(e) => onChange(e.target.valueAsNumber)}
/>
</label>
);
}The two forms differ when both sides declare the same property with different types:
extendsreports an error at the declaration, because the child's property type must be assignable to the parent's.&does not report at the declaration. It produces an intersection of the two property types. If they conflict, the property can becomenever, and the error shows up later at each use.
Prefer extends when you can, since it gives the earlier and clearer error.
You can also derive props from an existing type instead of repeating fields:
interface Product {
id: number;
name: string;
price: number;
description: string;
}
type ProductSummaryProps = Pick<Product, "name" | "price">;
type ProductFormProps = Omit<Product, "id"> & { onSave: (p: Omit<Product, "id">) => void };Deriving keeps the component in step with the data model. The cost is that a change to Product can change the component's public props without anyone editing the component. Use derived props when that coupling is intended.
Excess property checks and spread
TypeScript flags unknown properties only on fresh object literals and JSX attributes. This check is easy to bypass by accident.
interface AvatarProps {
src: string;
size: number;
}
function Avatar({ src, size }: AvatarProps) {
return <img src={src} width={size} height={size} alt="" />;
}
export function Demo() {
const config = { src: "/a.png", size: 32, rounded: true };
return (
<div>
{/* OK: spreading an existing object skips the excess property check */}
<Avatar {...config} />
{/* Error: Property 'rounded' does not exist on type 'AvatarProps' */}
{/* <Avatar src="/a.png" size={32} rounded /> */}
</div>
);
}An object stored in a variable, then spread, passes even with extra keys. The extra key is ignored at runtime by this component, but it can signal a typo. Do not rely on the compiler to catch misspelled props when you spread.
Avoid the loose escape hatches
Three patterns make a props type accept too much:
anyorobjectas a props type turns off checking for that component.- An index signature such as
[key: string]: unknownaccepts any property name, so typos pass. Functionas a callback type accepts any function and gives no parameter checking.
If a component really needs arbitrary extra attributes, extend the native element's props instead. A later chapter covers that.
How the check flows
Common errors
- Inline destructuring annotation.
function Box({ title: string })renames a variable. Annotate the whole parameter instead. - Using
objectfor props. It accepts anything non-primitive and lets you read no properties. - Required props that are sometimes missing. If a value may be absent, mark it optional or allow
undefined. Astring | undefinedprop is still required to be passed, but an optionaltitle?: stringis not. This difference is covered in the next chapter. - Mutable arrays. Typing a list as
string[]when the component never changes it rejects readonly arrays from callers. Usereadonly string[]. - Inferring props from a default. Props are not inferred from the function body. Without an annotation, destructured parameters have implicit
anyand fail understrict.
Exercise
A component is declared as function Rating({ value, max }: RatingProps). A teammate writes interface RatingProps { value: number } in one file and interface RatingProps { max: number } in another file in the same scope. The code compiles and Rating works. Explain why, and say what would change if both were type aliases.
Show answer
Interfaces with the same name in the same scope merge through declaration merging, so RatingProps has both value and max. With type aliases, the second declaration would be a "Duplicate identifier" compile error. Naming each props type after its component, and preferring one declaration per type, avoids the accidental merge.
Exercise
Write a props type for a Pagination component. It needs a page number, a pageCount number, and an onChange callback that receives the new page number and returns nothing. It also needs a labels list of strings that the component must not modify. Use an interface.
Show answer
interface PaginationProps { page: number; pageCount: number; onChange: (page: number) => void; labels: readonly string[]; } The callback uses property syntax with a void return, and readonly string[] blocks mutation while still accepting normal arrays.