TyepeScriptでReactRouterを扱う際に、URLパラメーターを取得するところで失敗した。
App.tsx
import React from 'react';
const Characters: React.FC<{}> = (props) => {
return (
<>
{props.match.params.name}
</>
);
}
export default Characters;
エラーメッセージは
Property 'match' does not exist on type '{ children?: ReactNode; }'. TS2339
RouteComponentPropsを用いる
matchはpropsに渡るオブジェクトに定義されてない。
そこでRouteComponentPropsとpropsの型を結合することでmatchが渡される。
App.tsx
import React from 'react';
+import { RouteComponentProps } from 'react-router';
+//interfaceの結合
+type urlProps = {} & RouteComponentProps<{name: string}>;
const Characters: React.FC<urlProps> = (props) => {
return (
<>
{props.match.params.name}
</>
);
}
export default Characters;
URLパラメーターが渡った
ちなみに...
VSCode上でRouteComponentPropsに左クリックしてGo to Definitionで定義ファイルを開くとmatchがプロパティにあることがわかる。
index.t.ts
export interface RouteComponentProps<Params extends { [K in keyof Params]?: string } = {},C extends StaticContext = StaticContext,S = H.LocationState>
{
history: H.History<S>;
location: H.Location<S>;
match: match<Params>;
staticContext?: C;
}