Give this code:
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 I try to access the config.tests[testName] immediately in the if block then it works fine.
However I'm getting "Object is possibly 'undefined'." on this line, even though I check for undefined above in the if condition.:
console.log(config.tests[name]);
console.log(config.tests[name]!);note the bang ! operator