Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Strengthen route typings #9366

Merged
merged 16 commits into from Sep 30, 2022
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions contributors.yml
Expand Up @@ -36,6 +36,7 @@
- goldins
- gowthamvbhat
- GraxMonzo
- GuptaSiddhant
- haivuw
- hernanif1
- hongji00
Expand Down
3 changes: 3 additions & 0 deletions packages/react-router-dom/index.tsx
Expand Up @@ -78,8 +78,10 @@ export type {
DataRouteObject,
Fetcher,
Hash,
IndexRouteObject,
IndexRouteProps,
JsonFunction,
LayoutRouteObject,
LayoutRouteProps,
LoaderFunction,
LoaderFunctionArgs,
Expand All @@ -97,6 +99,7 @@ export type {
PathMatch,
Pathname,
PathPattern,
PathRouteObject,
PathRouteProps,
RedirectFunction,
RelativeRoutingType,
Expand Down
3 changes: 3 additions & 0 deletions packages/react-router-native/index.tsx
Expand Up @@ -27,8 +27,10 @@ export type {
DataRouteObject,
Fetcher,
Hash,
IndexRouteObject,
IndexRouteProps,
JsonFunction,
LayoutRouteObject,
LayoutRouteProps,
LoaderFunction,
LoaderFunctionArgs,
Expand All @@ -46,6 +48,7 @@ export type {
PathMatch,
Pathname,
PathPattern,
PathRouteObject,
PathRouteProps,
RedirectFunction,
RelativeRoutingType,
Expand Down
24 changes: 24 additions & 0 deletions packages/react-router/__tests__/createRoutesFromChildren-test.tsx
Expand Up @@ -196,4 +196,28 @@ describe("creating routes from JSX", () => {
]
`);
});

it("throws when the index route has a path", () => {
expect(() => {
createRoutesFromChildren(
<Route path="/">
{/* @ts-expect-error */}
<Route index path="foo" />
</Route>
);
}).toThrow("An index route cannot have a path or child routes.");
});

it("throws when the index route has children", () => {
expect(() => {
createRoutesFromChildren(
<Route path="/">
{/* @ts-expect-error */}
<Route index>
<Route path="users" />
</Route>
</Route>
);
}).toThrow("An index route cannot have a path or child routes.");
});
});
6 changes: 6 additions & 0 deletions packages/react-router/index.ts
Expand Up @@ -64,8 +64,11 @@ import {
import type {
DataRouteMatch,
DataRouteObject,
IndexRouteObject,
LayoutRouteObject,
Navigator,
NavigateOptions,
PathRouteObject,
RouteMatch,
RouteObject,
RelativeRoutingType,
Expand Down Expand Up @@ -116,8 +119,10 @@ export type {
DataRouteObject,
Fetcher,
Hash,
IndexRouteObject,
IndexRouteProps,
JsonFunction,
LayoutRouteObject,
LayoutRouteProps,
LoaderFunction,
LoaderFunctionArgs,
Expand All @@ -135,6 +140,7 @@ export type {
PathMatch,
Pathname,
PathPattern,
PathRouteObject,
PathRouteProps,
RedirectFunction,
RelativeRoutingType,
Expand Down
58 changes: 23 additions & 35 deletions packages/react-router/lib/components.tsx
Expand Up @@ -26,6 +26,9 @@ import type {
RouteObject,
Navigator,
RelativeRoutingType,
PathRouteObject,
LayoutRouteObject,
IndexRouteObject,
} from "./context";
import {
LocationContext,
Expand Down Expand Up @@ -220,49 +223,28 @@ export function Outlet(props: OutletProps): React.ReactElement | null {
return useOutlet(props.context);
}

interface DataRouteProps {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got rid of the duplication here - <Route> props are now just RouteObject equivalents that expect ReactNode children instead of ReactElement children

id?: RouteObject["id"];
loader?: RouteObject["loader"];
action?: RouteObject["action"];
errorElement?: RouteObject["errorElement"];
shouldRevalidate?: RouteObject["shouldRevalidate"];
handle?: RouteObject["handle"];
}

export interface RouteProps extends DataRouteProps {
caseSensitive?: boolean;
children?: React.ReactNode;
element?: React.ReactNode | null;
index?: boolean;
path?: string;
}
// Create JSX-specific types from the RouteObjects, essentially changing
// ReactElement to ReactNode
export type PathRouteProps = Omit<PathRouteObject, "children"> & {
children?: React.ReactNode | null;
};

export interface PathRouteProps extends DataRouteProps {
caseSensitive?: boolean;
children?: React.ReactNode;
element?: React.ReactNode | null;
index?: false;
path: string;
}
export type LayoutRouteProps = Omit<LayoutRouteObject, "children"> & {
children?: React.ReactNode | null;
};

export interface LayoutRouteProps extends DataRouteProps {
children?: React.ReactNode;
element?: React.ReactNode | null;
}
export type IndexRouteProps = Omit<IndexRouteObject, "children"> & {
children?: undefined;
};

export interface IndexRouteProps extends DataRouteProps {
element?: React.ReactNode | null;
index: true;
}
export type RouteProps = PathRouteProps | LayoutRouteProps | IndexRouteProps;

/**
* Declares an element that should be rendered at a certain URL path.
*
* @see https://reactrouter.com/docs/en/v6/components/route
*/
export function Route(
_props: PathRouteProps | LayoutRouteProps | IndexRouteProps
): React.ReactElement | null {
export function Route(_props: RouteProps): React.ReactElement | null {
invariant(
false,
`A <Route> is only ever to be used as the child of <Routes> element, ` +
Expand Down Expand Up @@ -569,6 +551,12 @@ export function createRoutesFromChildren(
}] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>`
);

invariant(
!element.props.index ||
(element.props.path === undefined && !element.props.children),
"An index route cannot have a path or child routes."
);

let treePath = [...parentPath, index];
let route: RouteObject = {
id: element.props.id || treePath.join("-"),
Expand Down Expand Up @@ -619,7 +607,7 @@ export function enhanceManualRouteObjects(
if (routeClone.hasErrorBoundary == null) {
routeClone.hasErrorBoundary = routeClone.errorElement != null;
}
if (routeClone.children) {
if (!routeClone.index && routeClone.children) {
routeClone.children = enhanceManualRouteObjects(routeClone.children);
}
return routeClone;
Expand Down
27 changes: 22 additions & 5 deletions packages/react-router/lib/context.ts
Expand Up @@ -6,23 +6,40 @@ import type {
Router,
StaticHandlerContext,
To,
AgnosticRouteObject,
AgnosticRouteMatch,
AgnosticIndexRouteObject,
AgnosticLayoutRouteObject,
AgnosticPathRouteObject,
} from "@remix-run/router";
import type { Action as NavigationType } from "@remix-run/router";

// Create react-specific types from the agnostic types in @remix-run/router to
// export from react-router
export interface RouteObject extends AgnosticRouteObject {
export type IndexRouteObject = Omit<AgnosticIndexRouteObject, "children"> & {
children?: undefined;
Copy link

@lilonghe lilonghe Nov 22, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why children?: undefined;, maybe we can remove this line?

element?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
};
export type PathRouteObject = Omit<AgnosticPathRouteObject, "children"> & {
children?: RouteObject[];
element?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
}
};
export type LayoutRouteObject = Omit<AgnosticLayoutRouteObject, "children"> & {
children?: RouteObject[];
element?: React.ReactNode | null;
errorElement?: React.ReactNode | null;
};

export interface DataRouteObject extends RouteObject {
export type RouteObject =
| IndexRouteObject
| PathRouteObject
| LayoutRouteObject;

export type DataRouteObject = RouteObject & {
children?: DataRouteObject[];
id: string;
}
};

export interface RouteMatch<
ParamKey extends string = string,
Expand Down
40 changes: 39 additions & 1 deletion packages/router/__tests__/router-test.ts
Expand Up @@ -28,7 +28,7 @@ import {
} from "../index";

// Private API
import type { TrackedPromise } from "../utils";
import type { AgnosticRouteObject, TrackedPromise } from "../utils";
import { AbortedDeferredError } from "../utils";

///////////////////////////////////////////////////////////////////////////////
Expand Down Expand Up @@ -1002,6 +1002,44 @@ describe("a router", () => {
);
});

it("throws if it finds invalid route objects", async () => {
let routes: AgnosticRouteObject[] = [
// @ts-expect-error
{
path: "path",
index: true,
},
];
expect(() =>
createRouter({
routes,
history: createMemoryHistory(),
})
).toThrowErrorMatchingInlineSnapshot(
`"Cannot specify paths or children on an index route"`
);

routes = [
// @ts-expect-error
{
index: true,
children: [
{
path: "nope",
},
],
},
];
expect(() =>
createRouter({
routes,
history: createMemoryHistory(),
})
).toThrowErrorMatchingInlineSnapshot(
`"Cannot specify paths or children on an index route"`
);
});

it("supports a basename prop for route matching", async () => {
let history = createMemoryHistory({
initialEntries: ["/base/name/path"],
Expand Down
6 changes: 6 additions & 0 deletions packages/router/index.ts
Expand Up @@ -3,8 +3,14 @@ import { convertRoutesToDataRoutes } from "./utils";
export type {
ActionFunction,
ActionFunctionArgs,
AgnosticDataIndexRouteObject,
AgnosticDataLayoutRouteObject,
AgnosticDataPathRouteObject,
AgnosticDataRouteMatch,
AgnosticDataRouteObject,
AgnosticIndexRouteObject,
AgnosticLayoutRouteObject,
AgnosticPathRouteObject,
AgnosticRouteMatch,
AgnosticRouteObject,
TrackedPromise,
Expand Down