I'm currently in the process of developing a function API with a specific format:
createRoute('customers.view', { customerId: 1 }); // returns `/customers/1`
However, I am facing challenges when it comes to typing the first argument. This is my progress so far:
const uris = {
customers: {
view: '/customers/:customerId',
},
users: {
list: '/users',
}
};
const createRoute = (route: string, routeParams: { [key: string]: string }) => {
/**
* Splitting 'customer.view' into resource and action variables
*/
const [ resource, action ] = route.split('.');
/**
* Here's where I encounter an error:
*
* Element implicitly has an 'any' type because expression of type 'string'
* can't be used to index type '{ customers: { view: string; } }'.
*
*/
const uri = uris[resource]?.[action]
// ... additional code for replacing the route parameter...
};
I comprehend the meaning behind the error message. Although the function signature accepts any string
, it should be limited to valid keys within the uri
object.
Furthermore, the secondary split operation depends on the first one due to its nested nature.
Is there a way to define these types?