8000 fix(react): Make Route typing more generic (#3809) · jcomo/sentry-javascript@5f35c8c · GitHub
[go: up one dir, main page]

Skip to content

Commit 5f35c8c

Browse files
authored
fix(react): Make Route typing more generic (getsentry#3809)
DefinitelyTyped/DefinitelyTyped#51355 merging in lead to some more robust type inference for React Router params. This means that for Typescript >= 4.1.5, certain param types break when using the `withSentryRouting` higher order component. To fix this issue, we use a generic instead of a React component type for the wrapped React component. As we have to use this generic instead of a specific React type, we have to use @ts-ignore to make the JSX expressions work with typescript. Fixes getsentry#3808
1 parent 90eb35c commit 5f35c8c

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

packages/react/src/reactrouter.tsx

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -148,18 +148,26 @@ function computeRootMatch(pathname: string): Match {
148148
return { path: '/', url: '/', params: {}, isExact: pathname === '/' };
149149
}
150150

151-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
152-
export function withSentryRouting<P extends Record<string, any>>(Route: React.ComponentType<P>): React.FC<P> {
153-
const componentDisplayName = Route.displayName || Route.name;
151+
/* eslint-disable @typescript-eslint/no-explicit-any */
152+
export function withSentryRouting<P extends Record<string, any>, R extends React.ComponentType<P>>(Route: R): R {
153+
const componentDisplayName = (Route as any).displayName || (Route as any).name;
154154

155155
const WrappedRoute: React.FC<P> = (props: P) => {
156156
if (activeTransaction && props && props.computedMatch && props.computedMatch.isExact) {
157157
activeTransaction.setName(props.computedMatch.path);
158158
}
159+
160+
// @ts-ignore Setting more specific React Component typing for `R` generic above
161+
// will break advanced type inference done by react router params:
162+
// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/13dc4235c069e25fe7ee16e11f529d909f9f3ff8/types/react-router/index.d.ts#L154-L164
159163
return <Route {...props} />;
160164
};
161165

162166
WrappedRoute.displayName = `sentryRoute(${componentDisplayName})`;
163167
hoistNonReactStatics(WrappedRoute, Route);
168+
// @ts-ignore Setting more specific React Component typing for `R` generic above
169+
// will break advanced type inference done by react router params:
170+
// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/13dc4235c069e25fe7ee16e11f529d909f9f3ff8/types/react-router/index.d.ts#L154-L164
164171
return WrappedRoute;
165172
}
173+
/* eslint-enable @typescript-eslint/no-explicit-any */

0 commit comments

Comments
 (0)
0