Last updated: Feb 29, 2024
Reading timeยท2 min
To set optional props with default values in React TypeScript:
interface EmployeeProps { name?: string; // ๐๏ธ marked optional age?: number; // ๐๏ธ marked optional country: string; // ๐๏ธ required (no question mark) } function Employee({ name = 'Alice', age = 30, country, }: EmployeeProps) { return ( <div> <h2>{name}</h2> <h2>{age}</h2> <h2>{country}</h2> </div> ); } export default function App() { return ( <div> <Employee name="Bob" age={29} country="Belgium" /> <hr /> <Employee country="Austria" /> </div> ); }
We marked the name
and age
props as
optional.
name
and age
props.If a value for an optional prop is not specified, it gets set to undefined
.
Not providing a value for the prop and setting the prop to a value of
undefined
is the same.
We also set default values for the name
and age
parameters in the definition
of the Employee
component.
function Employee({ name = 'Alice', age = 30, country, }: EmployeeProps) { return ( <div> <h2>{name}</h2> <h2>{age}</h2> <h2>{country}</h2> </div> ); }
The name
property in the object is set to Alice
by default, so if the name
prop is not provided, it would get assigned a value of Alice
.
I've also written a detailed guide on how to use create-react-app with TypeScript.
props
object as optionalYou could also set the entire props
object as optional by marking all of its
properties as optional.
interface EmployeeProps { name?: string; // ๐๏ธ all marked optional age?: number; country?: string; } function Employee({ name = 'Alice', age = 30, country = 'Austria', }: EmployeeProps) { return ( <div> <h2>{name}</h2> <h2>{age}</h2> <h2>{country}</h2> </div> ); } export default function App() { return ( <div> <Employee name="Bob" age={29} country="Belgium" /> <hr /> <Employee /> </div> ); }
All of the properties in the EmployeeProps
type are marked as optional, so the
component can be used without being provided props.
We set default values for all of the props of the Employee
component, so if
any of the props are omitted, the default values are used.