tsc严格模式-如何使用提前返回来避免“对象可能是'undefined'”

时间:2019-08-31 21:43:21

标签: typescript tsc

我有这个:

  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);
  }

我收到此消息:

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

它必须是指lckTemp-但如果未定义,我会早点返回,有什么方法可以避免使用@ts-ignore编译消息吗?

我正在使用tsc --strict进行以下配置:

{
  "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 个答案:

答案 0 :(得分:0)

我不建议您告诉编译器忽略该警告,而是避免该警告:

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

这应该可以完成工作,因为exclamation mark告诉编译器lckTemp在此处不能为nullundefined。但是,我认为寻求早日回报并不十分吸引人,因此建议您像这样重组代码:

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);