ankitm
ankitm

Reputation: 195

Object possibly null even with default parameter value

I have this simple function, that takes a string and returns it in title case:

const toTitleCase = (str: string = 'test'): string => {
  const regex = /^[a-z]{0,1}|\s\w/gi;

  str = str.toLowerCase();

  str!.match(regex).forEach((char) => {
    str = str.replace(char, char.toUpperCase());
  });

  return str;
};

Even with the ! in str!.match as well as the default value for the parameter I get an "Object is possibly null" error from the TSC on that line. What gives?

Upvotes: 0

Views: 134

Answers (1)

Tadhg McDonald-Jensen
Tadhg McDonald-Jensen

Reputation: 21474

the part that is possibly null is str.match(regex) since if the regex doesn't find any matches it returns null instead of an empty list, so you would probably want to do this:

(str.match(regex) ?? []).forEach(...)

This indicates that if the match is undefined or null then use an empty list, although your regex is setup well to always match the beginning of a line so you would be safe to instead just use an assertion:

str.match(regex)!.forEach(...)

Upvotes: 1

Related Questions