【问题标题】:Nested destructuring possibly undefined maybe object嵌套解构可能未定义可能对象
【发布时间】:2022-08-23 22:33:00
【问题描述】:

我的自动生成的查询类型看起来像这样

export type MatchLivePlayerType = {
  __typename?: \'MatchLivePlayerType\';
  playbackData?: Maybe<MatchPlayerLivePlaybackDataType>;
};

export type MatchPlayerLivePlaybackDataType = {
  __typename?: \'MatchPlayerLivePlaybackDataType\';
  positionEvents?: Maybe<Array<Maybe<MatchLivePlayerPositionDetailType>>>;
};

export type MatchLivePlayerPositionDetailType = {
  __typename?: \'MatchLivePlayerPositionDetailType\';
  time: Scalars[\'Int\'];
  x: Scalars[\'Int\'];
  y: Scalars[\'Int\'];
};

对于如下的数据结果

{
  \"heroId\": 93,
  \"playbackData\": {
    \"positionEvents\": [
      {
        \"y\": 85,
        \"x\": 173,
        \"time\": 31
      }
    ]
  }
}

尝试进行嵌套解构时,我无法找到有效的方法来正确获取 positonEvents 并使用默认回退,而不会出现 TS 错误

Property \'positionEvents\' does not exist on type \'Maybe<MatchPlayerLivePlaybackDataType>\'
const defaultPositionEvents = {
  positionEvents: [
    {
      y: 0,
      x: 0,
      time: 0
    }
  ]
}
const { heroId, isRadiant, playbackData: { positionEvents } = defaultPositionEvents as MatchPlayerLivePlaybackDataType } = player;
  • 你的Maybe 类型是什么?

标签: javascript reactjs typescript


【解决方案1】:

您不能解构可能是 undefinednull 的嵌套对象

type Foo = {
    bar?: Bar
}

type Bar = {
    baz?: string
}

declare const foo: Foo;

const { bar: { baz } } = foo; // KO 

if (foo.bar) {
    const { bar: { baz } } = foo; // OK
}

缩小可以解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-11
    • 2022-01-20
    • 2020-08-11
    • 2021-11-29
    相关资源
    最近更新 更多