Home > Enterprise >  How to work with possible undefined values?
How to work with possible undefined values?

Time:09-21

I'm trying to work with an optional parameter, if said parameter is not included when calling the function, it is assigned a value automatically.

When using this parameter in the global scope of the function I do not receive any error from the linter, the problem appears when I try to use it inside a forEach (I have only tried there).

The following code is an example of what happens:

interface opts {
  optionalParam?: number
}

const func = (options: opts): void => {
  // I assign a value to the optional parameter
  options.optionalParam ??= 100

  const obj = {
    test: 8
  }
  obj.test = options.optionalParam * obj.test // ✅ It works perfect

  const objs = [{
    test: 6
  }]
  objs.forEach((obj) => {
    obj.test = options.optionalParam * obj.test // ❌ The object is possibly "undefined".ts(2532)
               ˆˆˆˆˆˆˆˆˆˆˆˆˆˆˆˆˆˆˆˆˆ
  })
}

I don't fully understand why in one place it detects it as undefined and in another it doesn't.

  • Related