Reactjs 为什么可以';t TypeScript是否看到不能取消定义嵌套值?

Reactjs 为什么可以';t TypeScript是否看到不能取消定义嵌套值?,reactjs,typescript,Reactjs,Typescript,TypeScript应该能够从三元运算符推断特定的嵌套值不能未定义。但事实并非如此。仅当我插入空断言运算符时,它才起作用插入到代码中,以指示值不是null或未定义 {!this.props.accounts[this.props.network] || this.props.accounts[this.props.network].address === undefined ? ( <div/>) : ( <OtherComponent address={this.

TypeScript应该能够从三元运算符推断特定的嵌套值不能未定义。但事实并非如此。仅当我插入空断言运算符
时,它才起作用插入到代码中,以指示值不是null或未定义

{!this.props.accounts[this.props.network] || this.props.accounts[this.props.network].address === undefined ? (
<div/>) : (
  <OtherComponent
    address={this.props.accounts[this.props.network].address}
  />
)
我有一个带有
道具
界面和
账户
字段的功能性react组件

export interface IAccountState {
  [key: string]: {
    address?: string;
  };
}

accounts: IAccountState;
在return语句中,我有一个三元运算符,用于检查值是否未定义

{!this.props.accounts[this.props.network] || this.props.accounts[this.props.network].address === undefined ? (
<div/>) : (
  <OtherComponent
    address={this.props.accounts[this.props.network].address}
  />
)
但是我认为TypeScript编译器应该能够看到由于三元运算符,地址值不能
未定义


我使用TypeScript 3.9.7,我的
tsconfig.json
设置了
“strictNullChecks”:true

这里最好的选择是给TypeScript一些更具体的东西,以缩小类型。在该JSX表达式之前:

{address === undefined ? (
<div/>) : (
  <OtherComponent
    address={address}
  />
)
const address=this.props.accounts[this.props.network]?.address;
或者不使用新的[ish]可选链接操作符:

const address=this.props.accounts[this.props.network]&&this.props.accounts[this.props.network].address;
然后在JSX表达式中:

{address === undefined ? (
<div/>) : (
  <OtherComponent
    address={address}
  />
)
{地址===未定义(
) : (
)

一个游乐场链接复制了一个简单示例中的问题,并显示保存到
常量
可以解决问题。

在JSX中,我们可能会使用
{address&&}
。React将忽略
null
未定义的
(不会在页面上显示为字符串)而且也没有无用的空
。@EmileBergeron-在另一种情况下,OP呈现的是
,而不是什么都没有。或者这是你的观点吗?这可能与流程或其他方面有关……是的,根据OP的开头,你的答案仍然是正确的;)