11

I am using the following code.

const body = /<body.*?>([\s\S]*)<\/body>/.exec(html)[1];

It compiles with the error below.

Object is possibly 'null'.ts(2531).

How can I fix it?

nyedidikeke
  • 6,899
  • 7
  • 44
  • 59
Harish
  • 1,841
  • 1
  • 13
  • 26
  • 4
    Check for a match first, before accessing the match results. This regex will cause issues if the text you match does not contain `

    ` tag and the text is large enough, BTW. And it will never match `

    ` tag that contains line breaks in between attributes. That is why regex is not a good idea when parsing HTML.
    – Wiktor Stribiżew Aug 24 '17 at 07:37
  • Look here https://stackoverflow.com/questions/40349987/how-to-suppress-typescript-error-ts2533-object-is-possibly-null-or-undefine – Piero Alberto Aug 24 '17 at 07:43
  • Thanks @PieroAlberto – Harish Aug 24 '17 at 10:46

2 Answers2

30

I am able to solve this question using non-null assertion operator ! as below

const body = /<body.*?>([\s\S]*)<\/body>/.exec(html)![1];
Harish
  • 1,841
  • 1
  • 13
  • 26
2

If you don't want to use the ! operator, one other option could be to use the optional operator ? and use a default value.

const body = /<body.*?>([\s\S]*)<\/body>/.exec(html)?[1] ?? '';
user023
  • 1,450
  • 2
  • 17
  • 21