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
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
The root cause is not related with optional chaining. The
obj
doesn’t containspage
on first level, so it will cause this warning. you should define the type ofobj
like this:and it should works.