打字稿:对象在循环 Object.keys() 时可能是 'undefined'
Typescript: Object is possibly 'undefined' while looping Object.keys()
输入代码:
interface Test {}
interface Config {
tests?: Record<string, Test>
}
const config: Config = {
tests: {
'test1': 'test1 implementation',
'test2': 'test2 implementation'
}
}
const readConfig = (config: Config) => {
const testName = 'test1'
if (config.tests) {
console.log(config.tests[testName]);
Object.keys(config.tests).forEach((name) => {
console.log(config.tests[name]);
})
}
}
readConfig(config);
如果我尝试在 if
块中立即访问 config.tests[testName]
那么它工作正常。
但是我得到“对象可能是 'undefined'”。在这条线上,即使我在 if
条件下检查上面的未定义。:
console.log(config.tests[name]);
首先尝试将 tests
放入它自己的标识符中。
const readConfig = (config: Config) => {
const testName = 'test1';
const { tests } = config;
if (tests) {
console.log(tests[testName]);
Object.keys(tests).forEach((name) => {
console.log(tests[name]);
})
}
}
您可能还想使用 Object.entries
来同时获取键和值 - 或者如果您只需要值,则只使用 Object.values
。
Object.entries(tests).forEach((name, value) => {
console.log(value);
})
输入代码:
interface Test {}
interface Config {
tests?: Record<string, Test>
}
const config: Config = {
tests: {
'test1': 'test1 implementation',
'test2': 'test2 implementation'
}
}
const readConfig = (config: Config) => {
const testName = 'test1'
if (config.tests) {
console.log(config.tests[testName]);
Object.keys(config.tests).forEach((name) => {
console.log(config.tests[name]);
})
}
}
readConfig(config);
如果我尝试在 if
块中立即访问 config.tests[testName]
那么它工作正常。
但是我得到“对象可能是 'undefined'”。在这条线上,即使我在 if
条件下检查上面的未定义。:
console.log(config.tests[name]);
首先尝试将 tests
放入它自己的标识符中。
const readConfig = (config: Config) => {
const testName = 'test1';
const { tests } = config;
if (tests) {
console.log(tests[testName]);
Object.keys(tests).forEach((name) => {
console.log(tests[name]);
})
}
}
您可能还想使用 Object.entries
来同时获取键和值 - 或者如果您只需要值,则只使用 Object.values
。
Object.entries(tests).forEach((name, value) => {
console.log(value);
})