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 propertymsg
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].
);
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