0

I have this:

  const lckTemp = this.locks.get(key);

  if (!lckTemp) {
    log.error('Missing lock for key:', key);
    return;
  }

  if (beginRead) {
    lckTemp.readers++
  }

  if (endRead) {
    // in case something weird happens, never let it go below 0.
    lckTemp.readers = Math.max(0, --lckTemp.readers);
  }

I am getting this message:

src/broker.ts(1201,11): error TS2532: Object is possibly 'undefined'.
src/broker.ts(1206,39): error TS2532: Object is possibly 'undefined'.

And it must be referring to lckTemp - but I return early if it's not defined, is there some way to avoid the compile message with @ts-ignore?

I am using tsc --strict with this configuration:

{
  "compilerOptions": {
    "skipLibCheck": true,
    "outDir": "dist",
    "declaration": true,
    "baseUrl": ".",
    "target": "es2018",
    "rootDir": "src",
    "module": "commonjs",
    "noImplicitAny": true,
    "removeComments": true,
    "allowUnreachableCode": false,
    "lib": [
      "es2017",
      "es2018"
    ]
  },
  "compileOnSave": false,
  "include": [
    "src"
  ]
}

1 Answers1

0

I would not suggest you to tell the compiler to ignore the warning, instead avoid it:

lckTemp!.readers = Math.max(0, --lckTemp!.readers);

This should do the job, because of the exclamation mark that tells the compiler that lckTemp cannot be null or undefined here. However, I think this is not very eye-candy looking to do an early return, so I'd suggest you to restructure your code like this:

const lckTemp = this.locks.get(key);

if (lckTemp) {

  if (beginRead) {
    lckTemp.readers++
  }

  if (endRead) {
    // in case something weird happens, never let it go below 0.
    lckTemp.readers = Math.max(0, --lckTemp.readers);
  }

  return;
}

log.error('Missing lock for key:', key);
Martin Braun
  • 10,906
  • 9
  • 64
  • 105