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
>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.