Suppose there is an interface called MyType
:
interface MyType {
options?: { field0: string, field1: string, field2: string };
}
If we are mapping over an array named myArray
, which has the type MyType[]
, we can destructure the options
attribute in this way:
myArray.map(({ options }) => {
const { field0, field1, field2 } = options!;
It's important to note the use of the bang operator (!
) as options
could potentially be undefined
.
I attempted to turn this into a one-liner like so:
myArray.map(({ options: { field0, field1, field2 }}) => {
However, this resulted in errors such as "Property 'field0' does not exist on type 'MyType | undefined'" due to the typing of options
.
In situations like this, usually I can include the bang operator to skip the undefined
check.
I tried doing it as a one-liner:
myArray.map(({ options: { field0, field1, field2 }!}) => {
and also:
myArray.map(({ options!: { field0, field1, field2 }}) => {
Both attempts were not valid syntax.
Is there a way to destructure an object that may be undefined
in a one-liner format within a parameter list?