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

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

Typescript : Object is possibly null

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

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

1 Answer

0 votes
by (71.8m points)

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]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...