Default Props
Loading "Default Props"
Run locally for transcripts
π¨βπΌ Sometimes you want to allow the user of your component to skip providing a
prop and use a default value instead. To do this, we can use
destructuring default values syntax,
but when users of our component try to skip a prop, TypeScript will complain
because our type says all the elements of the
CalculatorProps
type are
required.So when you make a prop optional, make sure you provide any relevant default
value as well as mark it as optional using the
optional properties syntax:
type User = { name: string; isCute?: boolean }
// name is required, isCute is optional, so these both compile:
const kody = { name: 'Kody', isCute: true }
const peter = { name: 'Peter' }
For this step, make all props optional. Default
left
and right
to
0
and operator
to '+'
. Then you can update the App to test it out:function App() {
return (
<div>
<h1>Calculator</h1>
<Calculator left={1} right={2} />
<Calculator operator="-" />
<Calculator left={1} operator="*" />
<Calculator operator="/" right={2} />
</div>
)
}