By the way, @david, I have a question for you.
Even if we use a data type guard like this:
// Get information about the current URL.
const data = state.source.get(state.router.link);
// Do nothing is this is not a post type.
if (!isPostType(data)) return null;
// Get the data of the post.
const post = state.source[data.type][data.id];
and data
is PostTypeData
after the if
, post
is any
.
That is because data.type
is string
in PostTypeData
and therefore TypeScript is not able to know the values.
If we use isPost
or isPage
, then it works:
// Get information about the current URL.
const data = state.source.get(state.router.link);
// Do nothing is this is not a post.
if (!isPost(data)) return null;
// Get the data of the post.
const post = state.source[data.type][data.id];
Now post
is PostEntity
. But that is not useful in case you have a single component for all the post types, like in mars:
<Switch>
<Post when={isPostType(data)} />
</Switch>
I see you have also used a trick to manually cast the type in a component by passing data
from the parent and typing the compnent, like this:
<Switch>
<Post when={isPostType(data)} data={data} />
</Switch>
const Post: React.FC<{ data: PostTypeData }> = ({ data }) => {
// ...
};
But that is not an ideal solution for all cases, in my opinion. It would be a bit like doing this:
// Get information about the current URL.
const data = state.source.get(state.router.link);
// Do nothing is this is not a post type.
if (!isPostType(data)) return null;
// Get the data of the post.
const post: PostTypeEntity = state.source[data.type][data.id];
So my question is… do we still need to add state.source.postTypes.xxx
and state.source.taxonomies.xxx
to solve this, or is there any other solution?
By the way, this would be the code in that case:
// Get information about the current URL.
const data = state.source.get(state.router.link);
// Do nothing is this is not a post type.
if (!isPostType(data)) return null;
// Get the data of the post.
const post = state.source.postTypes[data.type][data.id];
Also, right now I can’t figure out a way to get rid of the !isPostType(data)
check. The only one would be to do a manual cast in state.source.get()
:
// Get information about the current URL.
const data = state.source.get<PostTypeData>(state.router.link);
// Get the data of the post.
const post = state.source.postTypes[data.type][data.id];