Careeroza
Typing Props
Props with type / interface
type ButtonProps = {
label: string;
onClick: () => void;
variant?: 'primary' | 'secondary'; // optional, only these two values
disabled?: boolean;
};
function Button({ label, onClick, variant = 'primary', disabled = false }: ButtonProps) {
return <button className={variant} onClick={onClick} disabled={disabled}>{label}</button>;
}
const ok = <Button label="Save" onClick={() => save()} />; // ✓
const bad = <Button label="Save" variant="danger" />; // ✗ error: onClick missing, 'danger' not allowedchildren
import type { ReactNode } from 'react';
type CardProps = {
title: string;
children: ReactNode; // anything React can render
};
function Card({ title, children }: CardProps) {
return <section><h3>{title}</h3>{children}</section>;
}