I am creating a way to dynamically create routes before the server fully starts (meaning I’m not creating a route via a request lol that would be crazy), and I stumbled upon this interesting quirk.
Here is a minimal example. In the real program, there’s “post”, “patch”, etc. in the args, a path in the args, middleware, etc., but the result is all the same:
<code>export function createRoute(args: { search?: () => Promise<void> }) {
if (args.search) {
expressClient.get(
"",
async (req, res) => {
await args.search(); // Cannot invoke an object which is possibly 'undefined'
}
);
}
}
</code>
<code>export function createRoute(args: { search?: () => Promise<void> }) {
if (args.search) {
expressClient.get(
"",
async (req, res) => {
await args.search(); // Cannot invoke an object which is possibly 'undefined'
}
);
}
}
</code>
export function createRoute(args: { search?: () => Promise<void> }) {
if (args.search) {
expressClient.get(
"",
async (req, res) => {
await args.search(); // Cannot invoke an object which is possibly 'undefined'
}
);
}
}
Why is this happening?