diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index 3e9471e0ae..5c259f4a05 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -20,6 +20,7 @@ // Wesley Tsai // Sebastian Silbermann // Nicholas Hehr +// Pawel Fajfer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -161,7 +162,7 @@ export function useHistory(): H.History< export function useLocation(): H.Location; -export function useParams(): { [p in keyof Params]: string }; +export function useParams(): { [p in keyof Params]: keyof Params[p] extends undefined ? string | undefined : string }; export function useRouteMatch(): match; export function useRouteMatch( diff --git a/types/react-router/test/hooks.tsx b/types/react-router/test/hooks.tsx index 031d854826..269a3e04e1 100644 --- a/types/react-router/test/hooks.tsx +++ b/types/react-router/test/hooks.tsx @@ -5,6 +5,11 @@ interface Params { id: string; } +interface OptionalParams { + id?: string; + s: string | undefined; +} + interface LocationState { s: string; } @@ -14,6 +19,8 @@ const HooksTest: React.FC = () => { const location = useLocation(); const { id } = useParams(); const params = useParams(); + // $ExpectType { id?: string | undefined; s: string | undefined; } + const optionalParams = useParams(); // $ExpectType match | null const match1 = useRouteMatch('/:id'); // $ExpectType match | null @@ -27,6 +34,8 @@ const HooksTest: React.FC = () => { location.state.s; id && id.replace; params.id.replace; + optionalParams.id && optionalParams.id.replace; + optionalParams.s && optionalParams.s.replace; match1 && match1.params.id.replace; match2 && match2.params.id.replace; match3 && match3.params.id.replace;