typescript - 打字稿:使用变量作为键时检查记录属性是否未定义
问题描述
我有一个界面,里面有这样的记录
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"
},
解决方案
推荐阅读
- css - Webpack 4:mini-css-extract-plugin + 文件加载器不加载资产
- python - Keras自定义损失函数访问python全局变量的内部机制是什么?
- javascript - 需要帮助简化 Immutable.js 对象数组更新
- python - 在pytest中导入文件不匹配
- html - 如何使 Vimium 的元素可点击?
- firefox - Firefox 似乎无法为推送通知注册 ServiceWorker?
- python - 根据单元格值定位行
- reactjs - ReactJS - 在地图内循环图像的 src
- keyboard - " 按钮而不是我的外部键盘中的 <
- algorithm - Heapsort: Build max heap 过程解释