Home > database >  Need help understanding some typescript
Need help understanding some typescript

Time:11-10

I am looking at some typescript code for the first time and I'm clear on what it does until the last line. I believe that is a Nullish coalescing operator but I don't understand why the regex result is written matches?.[1] when matches[1] appears to work. Can anyone help with this?

const titleRegex = /<title(?:.*?)>(.*?)<\/title>/
const extractTitle = (website: string): string => {
  const matches = titleRegex.exec(website)
  return matches?.[1] ?? ''
}

CodePudding user response:

It is a protective approach. It would look similar to this without the grammar

if(matches != null && matches[1] != null) {
  return matches[1];
} else {
  return '';
}

CodePudding user response:

It's not a nullish coalescing operator but an optional chaining operator.

It's quite simple, it works like other optional chaining (meanings this code won't throw errors like "toto property doesn't exist on undefined" but will return undefined instead.

const data = {};
console.log(data?.toto);

the optional chaining can also be used to array elements or functions, like:

const toto = [1, 2, 3];
console.log(toto[1]);    // will print 2
console.log(toto?.[1]);  // will print 2
// Now let's imagine toto is undefined for whatever reasons
console.log(toto[42]);   // will throw "can't read property '42' of undefined"
console.log(toto?.[42]); // will print "undefined"

console.log("toto");     // will print "toto"
console.log?.("toto");   // will print "toto"
console.toto("toto");    // will throw an error "console.toto is not a function
console.toto?.("toto");  // will return "undefined"

And so far the regex.match routine will return:

An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.

Since it can be null, you'll need to handle the case where your data is either an array or null.

  • Related