网站搜索

reactjs - TS18048:'' 可能是 'undefined'


我正在使用 TypeScript,但我收到了错误 "TS18048: 'record.childList1' 可能是 'undefined'。",我猜这是因为 CheckListItemVO 中的 childList1 是可选的。我尝试写

  1. record.childList1[0]?.pciName
  2. (record.childList1[0] 作为 CheckListItemChildVO).pciName

但是仍然出现相同的错误。

这是我的代码

<Table.Column
   key='childList1'
   dataIndex='childList1'
   title={<div style={{ textAlign: 'center' }}>standard</div>}
   render={(text, record: CheckListItemVOExtender) => (
      <div style={{ display: 'flex', flexDirection: 'column' }}>
      <p style={{ whiteSpace: 'pre-wrap' }}>{record.childList1[0].pciName}</p>              
      </div>)}
/>

type CheckListItemVOExtender = CheckListItemVO & {
  sparPoint: string | number;
};

export type CheckListItemVO = CCheckListItem & {
  childList1?:CheckListItemChildVO[]; 
}

export type CCheckListItem = {
  pciName?:string; 
}

大多数时候,当我遇到错误时,我会加上可选标记或在末尾加上“as Type”(像第二种方法一样),但在这种情况下并没有用。

有人能帮忙吗?

答案#1

参见带表达式的可选链。

你也可以在方括号表示法中使用可选链操作符,这允许将表达式作为属性名传入
...
这对于数组特别有用,因为数组索引必须通过方括号访问

安全的语法是...

record.childList1?.[0]?.pciName
  • 第一个 ?.[0] 被使用是因为 childList1 可能是未定义的。
  • 第二个 ?.pciName 被使用是因为即使 childList1 是数组,它也可能是空的,并且 [0] 可能也是未定义的。

但是如果你只对第一个元素感兴趣,为什么childList1是一个数组呢?

例如,遍历数组是很典型的

<div style={{ display: 'flex', flexDirection: 'column' }}>
  {record.childList1?.map(({ pciName }, index) => (
    <p key={index} style={{ whiteSpace: 'pre-wrap' }}>
      {pciName}
    </p>
  ))}
</div>