Home > Enterprise >  Typescript - object is possibly null
Typescript - object is possibly null

Time:02-02

I am creating simple function to count all existing vowels in given string. I wrote function to do it but I cannot compile this with Typescript version higher than 3. I am curious how this function should be written to pass Typescript versions higher than 3.

function getCount(str: string = ''): number {
      return str.match(/[aeiou]/gi).length;
    }

test:

describe("getCount", function(){
    it ("should pass a sample test", function(){
        assert.strictEqual(getCount("abracadabra"), 5)
    });
});

With Typescript version 2.4 everything passes but with higher versions I am getting this:

error TS2531: Object is possibly 'null'.

CodePudding user response:

This is because .match() will return null if there is no match found.

If it is null then length cannot be used. You could save the outcome of str.match(/[aeiou]/gi) to a variable and then check it is not null. The resulting function could look like this:

function getCount(str: string = ''): number {
  let matched = str.match(/[aeiou]/gi);
  if(matched) return matched.length;
  else return 0;
}

Look here to find more about match.

  •  Tags:  
  • Related