Skip to content

React Props Types in TypeScript

interface ButtonProps {
label: string;
variant?: 'primary' | 'secondary' | 'danger';
size?: 'sm' | 'md' | 'lg';
disabled?: boolean;
onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
children?: React.ReactNode;
}
const Button: React.FC<ButtonProps> = ({ label, variant = 'primary', onClick, children }) => {
return <button className={`btn btn-${variant}`} onClick={onClick}>{label}{children}</button>;
};
interface ListProps<T> {
items: T[];
renderItem: (item: T, index: number) => React.ReactNode;
keyExtractor: (item: T) => string;
}
function List<T>({ items, renderItem, keyExtractor }: ListProps<T>) {
return <ul>{items.map((item, i) => <li key={keyExtractor(item)}>{renderItem(item, i)}</li>)}</ul>;
}

Easy: How do you type React props with TypeScript?

Medium: How do you make a generic component with typed props?

Hard: How would you type a polymorphic component’s ‘as’ prop?