0
export async function getSingleUserQA(command: Command, period?: string[]) {
  let slackUserID;

  if (command && command.text) {
    slackUserID = command.text.match("/(?<=@)(.*?)(?=|)/g")[0];
  }
}

I am being flagged that 'command' is possibly 'null' or 'undefined'. How come if I am making sure that command exists and command.text exists?

Charles Semaan
  • 304
  • 2
  • 13
  • 1
    `.match()` can return null – VLAZ Feb 13 '22 at 20:52
  • `command.text` could be changed outside the method. https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language – Blundell Feb 13 '22 at 20:53
  • @Blundell and yet would not matter because of the `if` check. – VLAZ Feb 13 '22 at 20:54
  • It's multithreaded so it does matter. (`async`) The value can change between the check and the next line invocation. ... *I think* :D – Blundell Feb 13 '22 at 20:58
  • @Blundell JS execution is *not* multithreaded in the vast majority of times. It could be *asynchronous* but still not parallel, since you have to explicitly opt into parallel execution and I sincerely doubt OP has done it. – VLAZ Feb 13 '22 at 21:09
  • Ah ok I understand, thanks! (Go back in my JVM box :D ) – Blundell Feb 13 '22 at 21:10

1 Answers1

1

Look closely at the warning. It's not saying that command might not exist, but that this whole expression:

command.text.match("/(?<=@)(.*?)(?=|)/g")

might not.

What do you want to do if the regular expression has no match? Figure that out, and guard it appropriately.

if (command && command.text) {
    const match = command.text.match("/(?<=@)(.*?)(?=|)/g");
    if (match) {
        slackUserID = match[0];
    } else {
        // handle badly formatted command
    }
}

You should also probably do

let slackUserID: string;

or only use the result inside the conditional.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320