Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How to avoid Object is possibly null in VSCode though code runs ok

  let url = 'https://test.com/test/varstring/stringtoextract?id=test3'
  let regex = /https://test.com/test/varstring/.+/(.+)?.+/
  var match = regex.exec(url);
  alert(match[1]); 
question from:https://stackoverflow.com/questions/66052881/typescript-object-is-possibly-null

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
626 views
Welcome To Ask or Share your Answers For Others

1 Answer

If you are sure, use the Non-null assertion operator !:

alert(match![1]);

Of course, an if statement would also do the trick:

if (match) {
    alert(match[1]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...