Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/fix-exact-optional-property-types.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
"react-router": patch
"@react-router/dev": patch
---

Fix TypeScript compatibility with `exactOptionalPropertyTypes: true`

When `exactOptionalPropertyTypes` is enabled in `tsconfig.json`, TypeScript requires that optional properties explicitly allow `undefined` values. The generated types from `react-router typegen` were causing type errors because the `RouteModule` type constraint didn't explicitly allow `undefined` for optional properties like `action`, `loader`, etc.

This change updates the `RouteModule` type definition to explicitly include `| undefined` for all optional properties, making it compatible with `exactOptionalPropertyTypes: true`.

Fixes #14734
1 change: 1 addition & 0 deletions contributors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -471,3 +471,4 @@
- zeromask1337
- zheng-chuang
- zxTomw
- 0372hoanghoccode
60 changes: 60 additions & 0 deletions integration/typegen-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,66 @@ test.use({
});

test.describe("typegen", () => {
test("exactOptionalPropertyTypes compatibility", async ({ edit, $ }) => {
await edit({
"tsconfig.json": tsx`
{
"include": [
"**/*.ts",
"**/*.tsx",
"**/.server/**/*.ts",
"**/.server/**/*.tsx",
"**/.client/**/*.ts",
"**/.client/**/*.tsx"
],
"compilerOptions": {
"lib": ["DOM", "DOM.Iterable", "ES2022"],
"types": ["@react-router/node", "vite/client"],
"isolatedModules": true,
"esModuleInterop": true,
"jsx": "react-jsx",
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"target": "ES2022",
"strict": true,
"exactOptionalPropertyTypes": true,
"allowJs": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"paths": {
"~/*": ["./app/*"]
},
"noEmit": true
}
}
`,
"app/routes.ts": tsx`
import { type RouteConfig, route } from "@react-router/dev/routes";

export default [
route("products/:id", "routes/product.tsx")
] satisfies RouteConfig;
`,
"app/routes/product.tsx": tsx`
import type { Expect, Equal } from "../expect-type"
import type { Route } from "./+types/product"

export function loader({ params }: Route.LoaderArgs) {
type Test = Expect<Equal<typeof params, { id: string} >>
return { planet: "world" }
}

export default function Component({ loaderData }: Route.ComponentProps) {
type Test = Expect<Equal<typeof loaderData.planet, string>>
return <h1>Hello, {loaderData.planet}!</h1>
}
`,
});
await $("pnpm typecheck");
});

test("basic", async ({ edit, $ }) => {
await edit({
"app/routes.ts": tsx`
Expand Down
2 changes: 1 addition & 1 deletion packages/react-router-dev/__tests__/route-config-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const cleanPathsForSnapshot = (obj: any): any =>
JSON.parse(
JSON.stringify(obj, (_key, value) =>
typeof value === "string" && path.isAbsolute(value)
? normalizePath(value.replace(process.cwd(), "{{CWD}}"))
? normalizePath(value).replace(normalizePath(process.cwd()), "{{CWD}}")
: value,
),
);
Expand Down
51 changes: 39 additions & 12 deletions packages/react-router-dev/typegen/generate.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,40 @@
import ts from "dedent";
import * as fs from "node:fs";
import * as Path from "pathe";
import * as Pathe from "pathe/utils";
import * as TS from "typescript";

import type { RouteManifestEntry } from "../config/routes";
import * as Babel from "../vite/babel";
import type { Context } from "./context";
import * as Params from "./params";
import * as Route from "./route";
import type { RouteManifestEntry } from "../config/routes";

export type VirtualFile = { filename: string; content: string };

/**
* Detect if the project has exactOptionalPropertyTypes enabled in tsconfig.json
*/
function hasExactOptionalPropertyTypes(ctx: Context): boolean {
const tsconfigPath = Path.join(ctx.rootDirectory, "tsconfig.json");
try {
if (!fs.existsSync(tsconfigPath)) return false;

const configFile = TS.readConfigFile(tsconfigPath, TS.sys.readFile);
if (configFile.error) return false;

const parsedConfig = TS.parseJsonConfigFileContent(
configFile.config,
TS.sys,
ctx.rootDirectory,
);

return parsedConfig.options.exactOptionalPropertyTypes === true;
} catch {
return false;
}
}

export function typesDirectory(ctx: Context) {
return Path.join(ctx.rootDirectory, ".react-router/types");
}
Expand Down Expand Up @@ -180,10 +205,10 @@ function routeFilesType({
t.tsTypeAnnotation(
pages
? t.tsUnionType(
Array.from(pages).map((page) =>
t.tsLiteralType(t.stringLiteral(page)),
),
)
Array.from(pages).map((page) =>
t.tsLiteralType(t.stringLiteral(page)),
),
)
: t.tsNeverKeyword(),
),
),
Expand All @@ -208,12 +233,12 @@ function routeModulesType(ctx: Context) {
t.tsTypeAnnotation(
isInAppDirectory(ctx, route.file)
? t.tsTypeQuery(
t.tsImportType(
t.stringLiteral(
`./${Path.relative(ctx.rootDirectory, ctx.config.appDirectory)}/${route.file}`,
),
t.tsImportType(
t.stringLiteral(
`./${Path.relative(ctx.rootDirectory, ctx.config.appDirectory)}/${route.file}`,
),
)
),
)
: t.tsUnknownKeyword(),
),
),
Expand Down Expand Up @@ -286,13 +311,15 @@ function getRouteAnnotations({
Path.resolve(ctx.config.appDirectory, file),
);

const useStrictOptionals = hasExactOptionalPropertyTypes(ctx);

const content =
ts`
// Generated by React Router

import type { GetInfo, GetAnnotations } from "react-router/internal";
import type { GetInfo, GetAnnotations, StrictOptionals } from "react-router/internal";

type Module = typeof import("${routeImportSource}")
type Module = ${useStrictOptionals ? "StrictOptionals<" : ""}typeof import("${routeImportSource}")${useStrictOptionals ? ">" : ""}

type Info = GetInfo<{
file: "${file}",
Expand Down
Loading
Loading