Say we have a TypeScript interface with required and optional values.
interface NonosOptions {
thickness: number,
pressure?: number
}
thickness
is required, pressure
is optional.
If we create an object of type NonosOptions
, we can omit pressure
but not thickness
.
const options: NonosOptions = {
thickness: 1.5
}
We can now deconstruct our options
with a default pressure value, which will only be used if options
doesn't define a value.
const { thickness = 2, pressure = 0.75 } = options
// thickness = 1.5
// pressure = 0.75
As you can see, thickness
ignores the 2
assignment because options
sets it as 1.5
.
But pressure
is set to 0.75
because options
doesn't define a pressure
value.
If pressure
is defined in options
, both thickness
and pressure
deconstruction fallback values would be ignored.
const options: NonosOptions = {
thickness: 1.5,
pressure: 0.25
}
const { thickness = 2, pressure = 0.75 } = options
// thickness = 1.5
// pressure = 0.25