Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get Typescript to allow optional chaining to be undefined without warning message?

In the example below, Typescript keeps warning that obj?.[type] implicitly has an any type. I want the callback to be able to be undefined or a function since I’m checking it afterwards. I want to keep the obj dynamic and not explicitly provide the type for it. How can I tell typescript to allow for this optional chaining statement to pass without a warning message?


const obj = {
    row: {
        over: {
            page: () => { },
        },
    },
    col: {
        over: {
            page: () => { }
        }
    },
    el: {
        over: {
            page: () => { },
            row: () => { },
        }
    }
};

function myFn(type: "page" | "row" | "col" | "el") {
    const callback = obj?.[type]?.over?.[type];
    if (callback) {
        console.log("has callback");
    }
    console.log("no callback");
}

Typescript Playground: link

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The root cause is not related with optional chaining. The obj doesn’t contains page on first level, so it will cause this warning. you should define the type of obj like this:

const obj: Record<string, { over: Record<string, () => void> }> = {
    // ...
};

and it should works.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading