最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Flowtype property 'msg' is missing in null or undefined - Stack Overflow

programmeradmin2浏览0评论

I am finding hard to use Flow. I understand that Array.find can return or be undefined.

So by reading this: github: Array.find on Array<{...}> raises

I did that and added void to the type to. However now I get the error:

Cannot get stageMsg.msg because property msg is missing in null or undefined (see line 92).

Check code to see where the error is specifically.

I understand why it is giving me the error, there is no msg in undefined. what I don't know is how to solve this issue.

Here is the code:

type StageMsg = {
  stage: number,
  msg?: string
};

let stageMsg: void | StageMsg = this.stages.find(
  (obj: StageMsg) => obj.stage === this.state.stage
);

msg = (
  <Msg text={this.state.msg !== "" ? this.state.msg : stageMsg.msg} /> //<---- [Error here].
);

I am finding hard to use Flow. I understand that Array.find can return or be undefined.

So by reading this: github: Array.find on Array<{...}> raises

I did that and added void to the type to. However now I get the error:

Cannot get stageMsg.msg because property msg is missing in null or undefined (see line 92).

Check code to see where the error is specifically.

I understand why it is giving me the error, there is no msg in undefined. what I don't know is how to solve this issue.

Here is the code:

type StageMsg = {
  stage: number,
  msg?: string
};

let stageMsg: void | StageMsg = this.stages.find(
  (obj: StageMsg) => obj.stage === this.state.stage
);

msg = (
  <Msg text={this.state.msg !== "" ? this.state.msg : stageMsg.msg} /> //<---- [Error here].
);
Share Improve this question edited Sep 3, 2020 at 11:11 mkrieger1 23.5k7 gold badges64 silver badges82 bronze badges asked Nov 14, 2018 at 14:11 Rip3rsRip3rs 1,57013 silver badges22 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

You just need to check that stageMsg exists before accessing a property on it.
So you could wrap your assigment to msg in if (stageMsg) { ... }, or use an inline expression like stageMsg && stageMsg.msg.
Also note that you could use maybe syntax instead of a union with void e.g. let stageMsg: ?StageMsg

发布评论

评论列表(0)

  1. 暂无评论