Im receiving a parameter, that can be an array that contain many literal objects or an literal object directly.
This is the method:
public add(optionsStack: RTypes.RouteParam): this {
if (Array.isArray(optionsStack)) {
optionsStack.forEach((routeItem: RTypes.Route) => {
// Check if any property wasn't gived
ok(routeItem.path);
ok(routeItem.method);
ok(routeItem.requestHandler);
// Covering problem that may exist
routeItem.method = routeItem.method.toUpperCase();
this.routes.push(routeItem);
});
};
if (Object.getPrototypeOf(optionsStack) === Object.prototype) {
ok(optionsStack.path);
ok(optionsStack.method);
ok(optionsStack.requestHandler);
// Covering problem that may exist
optionsStack.method = optionsStack.method.toUpperCase();
this.routes.push(optionsStack);
};
return this;
When I give an array with objects, the function works as I expect here:
I have delete the part that check only for literal objects to show this console.log (In that part is the error)
router.add([
{
path: "/",
method: "get",
requestHandler: ((req, res) => {
res.end("<h1>Hello World!</h1>");
})
},
{
path: "/about",
method: "get",
requestHandler: ((req, res) => {
res.end("<h1>Hello World from About Page!</h1>");
})
},
])
Terminal output:
HRouter {
routes: [
{
path: '/',
method: 'GET',
requestHandler: [Function: requestHandler]
},
{
path: '/about',
method: 'GET',
requestHandler: [Function: requestHandler]
}
]
}
But in the method I get some errors, like:
The property 'path' dont exist on type 'RouteParam'
The property 'path' dont exist on type 'Route[]'
The property 'method' dont exist on type 'RouteParam'
The property 'method' dont exist on type 'Route[]'
The property 'requestHandler' dont exist on type 'RouteParam'
The property 'requestHandler' dont exist on type 'Route[]'
Can not assign an argument of type "RouteParam" to parameter of type "Route"
The type "Route" is missing the following properties from type "Route": path, method, requestHandler
And here is the types used in the method:
import { RequestListener } from "node:http"
export interface Route {
path: string;
method: string;
requestHandler: RequestListener;
};
export type RouteParam = Route | Route[]
How I can fix it?. Thanks :)