[英]Nested destructuring possibly undefined maybe object
My auto generated query types look something like this我的自动生成的查询类型看起来像这样
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'];
};
For a data result like the following对于如下的数据结果
{
"heroId": 93,
"playbackData": {
"positionEvents": [
{
"y": 85,
"x": 173,
"time": 31
}
]
}
}
When attempting to do nested destructuring I'm unable to find a valid way to correctly get positonEvents
with a default fallback without getting a TS error for当尝试进行嵌套解构时,我无法找到一种有效的方法来正确获取具有默认回退的
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;
You can't destructure a nested object that might be undefined
or null
您不能解构可能
undefined
的嵌套 object 或null
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
}
Narrowing fixes the problem.缩小可以解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.