1

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]);
1
  • You can assert the value is present like so: console.log(config.tests[name]!); note the bang ! operator Commented Jul 8, 2021 at 8:01

1 Answer 1

2

Try putting the tests into its own identifier first.

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

You also might want to use Object.entries to get both the key and value at once - or just Object.values if you only need the value.

Object.entries(tests).forEach((name, value) => {
    console.log(value);
})
Sign up to request clarification or add additional context in comments.

1 Comment

Object.entries(tests).forEach(([name, value]) => { console.log(name, value); }) works best in my case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.