Typescript: Object is possibly ‘undefined’

There are two ways to that I can think of to get rid of the error.

The first way I can think of is to use a fallback with the || operator, which would turn this:

a[k].toString().toLowerCase()

Into this, so if the value is falsy, then use an empty string.

(a[k] || '').toString().toLowerCase()
// Or with optional chaining
a[k]?.toString().toLowerCase() || ''

Note: Use ?? to catch only undefined and null values instead of falsy values.

The other way is to save the value to a variable and check the new variable. Which then makes this

if (a && a[k]) {
  return textMatch(txt.toLowerCase(), a[k].toString().toLowerCase()) ? a : null;
}

Become this:

let v = a ? a[k] : null
if (v) {
  return textMatch(txt.toLowerCase(), v.toString().toLowerCase()) ? a : null;
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)