英文:
Destructure an object that has the possibility of being undefined as a one-liner in a parameter list
问题
给定一个接口 `MyType`:
```tsx
interface MyType {
options?: { field0: string, field1: string, field2: string };
}
在对类型为 MyType[]
的数组 myArray
进行映射时,可以像这样解构 options
属性:
myArray.map(({ options }) => {
const { field0, field1, field2 } = options!;
注意感叹号 (!
),因为 options
可能为 undefined
。
我试图将其转化为一行代码,如下所示:
myArray.map(({ options: { field0, field1, field2 }}) => {
但是,这会导致错误,类似于“属性 'field0' 不存在于类型 'MyType | undefined'”,这是因为 options
的类型方式而导致的。
通常在这种情况下,我可以添加感叹号运算符来绕过 undefined
检查。
我尝试过:
myArray.map(({ options: { field0, field1, field2 }!}) => {
和:
myArray.map(({ options!: { field0, field1, field2 }}) => {
...但是这两种尝试都不是语法上有效的。
是否有一种方法可以在参数列表中将可能为 undefined
的对象解构为一行代码?
<details>
<summary>英文:</summary>
Given an interface `MyType`:
```tsx
interface MyType {
options?: { field0: string, field1: string, field2: string };
}
Mapping over an array, myArray
, which has type MyType[]
, one can destructure the options
attribute like this:
myArray.map(({ options }) => {
const { field0, field1, field2 } = options!;
Note the bang (!
), because options
could be undefined
.
I was trying to turn this into a one-liner, like this:
myArray.map(({ options: { field0, field1, field2 }}) => {
But, this results in errors like "Property 'field0' does not exist on type 'MyType | undefined'" which makes sense because of the way options
is typed.
Usually in this scenario I can add the bang operator to bypass the undefined
check.
I tried:
myArray.map(({ options: { field0, field1, field2 }!}) => {
and:
myArray.map(({ options!: { field0, field1, field2 }}) => {
...but neither attempts are syntactically valid.
Is there a way to destructure an object that has the possibility of being undefined
as a one-liner in a parameter list?
答案1
得分: 4
如果您确定数组仅包含具有“options”属性的对象,可以在数组本身上使用类型断言:
(myArray as Required<MyType>[]).map(({ options: { field0, field1, field2 }}) => {
另一种允许您使用非空断言的替代方法是在两个步骤中使用map
:
myArray.map(el => el.options!).map({ field0, field1, field2 }) => {
然而,处理这种情况的正确安全方式是预期一些数组元素实际上可能没有“options”,并将它们默认为一个空对象:
myArray.map(({ options: { field0, field1, field2 } = {}}) => {
英文:
If you are sure that the array contains only objects with options
, you can use a type assertion on the array itself:
(myArray as Required<MyType>[]).map(({ options: { field0, field1, field2 }}) => {
An alternative that lets you use the non-null assertion is map
ping in two steps:
myArray.map(el => el.options!).map({ field0, field1, field2 }) => {
However, the proper safe way to handle this is to anticipate that some array elements actually might have no options
, and default those to an empty object:
myArray.map(({ options: { field0, field1, field2 } = {}}) => {
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论