Add TypeScript Type Checks to RouteData fields
All the world's a type and we are all merely types
RouteData is an interface defined as:
In other words,
RouteData.fields acts as a kind of arbitrary dictionary.
Now imagine that I have defined a custom type (the full type actually has 25+ fields):
I'd like to be able to do this:
However, I get this IDE / build error:
If I do as the error suggests, the IDE and build gods are pleased:
Let's say you need a component that renders a header for a "blog" page. The header should display the title of the blog and the type of blog. Both fields are specified on the page item (and therefore the route). The blog type is a list field that is a reference to a custom type called
BlogType has a single field called
Name. The header component should be able to render the title and the name of the blog type.
The Better Solution
sitecoreContext has no knowledge of what RouteData it has; specifically,
fields. It defaults to
Record<string, string | Field | Item | Item>, which means we need to assert what is in it when we use it.
The better solution to this would be to have a generic type for
RouteData that allows us to specify the type of
fields. If generics were supported we could do this:
This is cleaner and more less prone to errors because assertions don't need to be added whenever route fields are referenced. I am also not the first one to notice or ask for this:
The OP describes the ask perfectly and offers a temporary solution until someone takes the precious time to submit a PR.