Replies: 1 comment 1 reply
-
Meanwhile, here's a user-land implementation which does what I have in mind: type GetKnownMatches<Matches> = Matches extends [
infer M extends { id: unknown },
...infer Tail extends unknown[],
]
? M | GetKnownMatches<Tail>
: never;
type GetKnownIds<Matches> = GetKnownMatches<Matches>["id"];
export function matchById<
Matches extends ({ id: unknown } | undefined)[],
const Id extends GetKnownIds<Matches>,
>(matches: Matches, id: Id): GetKnownMatches<Matches> & { id: Id } {
return matches?.find(
(match) => match?.id === id,
) as GetKnownMatches<Matches> & {
id: Id;
};
} Example usage: export default function ClientInfo({
matches,
}: Route.ComponentProps) {
const { application } = matchById(matches, "routes/clientDetails").data;
// the rest of the component...
} It would be great to have this included natively :) |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
The new typesafe
matches
is a really cool API a godsend.useMatches
was nice, but felt "wrong" due to the lack of typesafey, whereas now I've started using it with confidence.My typical use case is to fetch some data in a top-level loader, which will be also used by some nested routes. Using
matches
allows me to directly access the data instead of refetching it in the downstream loader.Let's consider an application structured like:
Now when I'm the
ClientInfo
route I might do something like this:The cool thing about the new type safety is that if I now add a layout around the whole thing:
Then the code fails to compile, because
matches[1]
is now the client layout, and not the client details, and its data do not include aclient
. I now need to update the code like this:While it's great that TypeScript catches these, wouldn't it be cool if we could reference the
matches
data by route id instead?That would look something like this:
Now the code is still type-safe, but with two main advantages:
matches["routes/clientDetails"]
is more readable thanmatches[1]
Would an API like this be possible? Given that the tuple type of matches already has
ids
I feel like this could be achievable. Also, runtime-wise, it could probably be added in a backward compatible fashion, since supporting indexed access alongside named access should be easy.Beta Was this translation helpful? Give feedback.
All reactions