Typing component props
A component's props are its public API. When a caller passes the wrong one, you
want to hear about it before the app runs — not from a blank screen. An
interface (or type) names the shape, and the component annotates its
parameter with it:
interface GreetingProps {
name: string;
greeting?: string;
}
function Greeting({ name, greeting }: GreetingProps) {
return (
<p>
{greeting}, {name}
</p>
);
}
The ? marks a prop as optional. TypeScript insists you pass name, but lets
greeting be left out. When a prop is optional you usually give it a default in
the destructuring pattern, which also narrows it back to a plain string inside
the component:
function Greeting({ name, greeting = 'Hello' }: GreetingProps) {
// greeting is string, never undefined
}
Now the interface is checked at every call site: miss a required prop or pass the wrong type and the compiler tells you. The type is erased at build time, so it costs nothing at runtime — it is documentation the compiler can verify.
Your job is to type a component's props in App.tsx and give an optional
prop a default.
Challenge
A greeting component ignores its props and always shows the same line. Export an
App component from App.tsx that renders a Greeting component with name
set to "Ada". Give Greeting a props interface with a required name and an
optional greeting that defaults to "Hello", and have it render a paragraph
reading <greeting>, <name>.
The Test renders your component and expects the paragraph to read Hello, Ada.
The starter renders a fixed paragraph, so the Test fails.