skip to Main Content

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

2

Answers


  1. You can add this comment at the beginning of the file to avoid type checking:

    // @ts-nocheck

    However you’re also getting an error from a missing property there

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search