首页 > 解决方案 > 打字稿:使用变量作为键时检查记录属性是否未定义

问题描述

我有一个界面,里面有这样的记录

interface Foo {
    bar: Record<string, barz>;
}
interface barz {
    j:string[]
}

现在我想在一个结果数组中收集所有 Js,所以我循环遍历键

const foo: Foo = {
    bar: {
      test: {
        j: ['value']
      }
    }
  };  

let result: string[] = [];
  
for (const key of Object.keys(foo.bar)) {
  // Key should be 'test'
  if (foo.bar[key]) {
      result.push(...foo.bar[key].j);
  }
}

现在它告诉我foo.bar[key]即使我检查了 if 也可能是未定义的。如何在不使用的情况下让 typescript 快乐//@ts-ignore

编辑:在我的 tsconfig.json 中:

"compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@src": ["src/index.ts"],
      "@src/*": ["src/*"]
    },
    "target": "ES2020",
    "module": "CommonJS",
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "outDir": "./dist/unknown",
    "removeComments": false,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictBindCallApply": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "noUncheckedIndexedAccess": true,
    "noPropertyAccessFromIndexSignature": false,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "preserveSymlinks": true,
    "typeRoots": ["node_modules/@types"],
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": false,
    "newLine": "LF"
  },

标签: typescript

解决方案


推荐阅读