TypeScript
/Beginner
React: Typing Props
Definition
Using TypeScript Interfaces or Type Aliases to define the exact shape of properties (props) a React component accepts.
Explain Like I'm New
Typing props is giving your React component a bouncer at the door. If a parent component tries to pass a prop that isn't on the guest list (the Interface), or tries to pass a Number when a String was expected, the bouncer rejects it instantly.
Real World Example
Typing a ProfileCard component to require a `name: string` and an `age: number`, with an optional `avatarUrl?: string`.
Common Use Cases
- •Self-documenting React components
- •Preventing UI crashes from missing data
Interactive Example
import React from 'react'; type ButtonProps = { label: string; // Required string onClick: () => void; // Required function isDisabled?: boolean; // Optional boolean children?: React.ReactNode; // Optional React elements inside the tag }; // Modern approach: Typing the arguments directly export function Button({ label, onClick, isDisabled = false, children }: ButtonProps) { return ( <button onClick={onClick} disabled={isDisabled}> {label} {children} </button> ); } // USAGE (TS will throw an error if 'label' or 'onClick' are missing!) // <Button label="Submit" onClick={() => console.log('Clicked')} />
Interview Questions
basic
- Should you use `type` or `interface` for React Props?
intermediate
- How do you type a prop that accepts React children (like `<div>...</div>`)?
advanced
- What is `React.FC` and why is it currently discouraged by many developers?