0

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'.

1
  • It seems strange to give a default value to the str , since you're counting the number of vowels in a string, the string should be required? Maybe consider removing the initial value Commented Feb 1, 2022 at 17:53

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I saw that too, thanks for your answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.