← Back to TypeScript Course | Chapter 14: TypeScript with React | Lesson 2 of 8

Typing Props

Props are values passed from a parent component to a child component. TypeScript interfaces or type aliases can describe exactly which props a component expects.

Basic Props

Basic props are typed with an interface listing each prop name and its type, which the component then destructures from a single typed parameter, giving callers immediate feedback if they pass the wrong type or a missing prop.

Example: Basic Props

typescript
import React from "react";

interface GreetingProps {
	name: string;
}

function Greeting({ name }: GreetingProps): React.JSX.Element {
	return <p>Hello, {name}</p>;
}

export default Greeting;

Optional Props

An optional prop is marked with a ? in its interface, meaning callers can omit it entirely, and inside the component that prop's type includes undefined unless you supply a default value for it.

Example: Optional Props

typescript
import React from "react";

interface ButtonProps {
	label: string;
	disabled?: boolean;
}

function Button({ label, disabled }: ButtonProps): React.JSX.Element {
	return <button disabled={disabled}>{label}</button>;
}

export default Button;

Function Props

A function prop is typed with a specific call signature — like onClick: () => void — so passing something with the wrong parameter count or return type gets flagged at the call site, not at runtime when the function actually fires.

Example: Function Props

typescript
import React from "react";

interface ClickableProps {
	onClick: () => void;
}

function Clickable({ onClick }: ClickableProps): React.JSX.Element {
	return <button onClick={onClick}>Click</button>;
}

export default Clickable;

Children Props

Children props are typed with React's ReactNode type (covering JSX, strings, numbers, and more), which is what lets a component accept nested JSX between its opening and closing tags in a type-safe way.

Example: Children Props

typescript
import React, { ReactNode } from "react";

interface CardProps {
	children: ReactNode;
}

function Card({ children }: CardProps): React.JSX.Element {
	return <div className="card">{children}</div>;
}

export default Card;

Props with Union Types

A prop typed as a union — like variant: primary | secondary — restricts callers to a fixed, known set of string values instead of any arbitrary string, catching a typo like primry immediately at the call site.

Example: Props with Union Types

typescript
import React from "react";

interface AlertProps {
	variant: "primary" | "secondary";
}

function Alert({ variant }: AlertProps): React.JSX.Element {
	return <div className={variant}>Alert</div>;
}

export default Alert;
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.