简体   繁体   中英

By typescript, how to declare a member of specific ReactElement type in interface

I want to limit an interface member type for <Route ... /> only, the codes below seems not working.

import React, { ReactElement } from "react";
import { Route, RouteProps } from 'react-router-dom';

import Menu from 'feature/system/menu/Menu';

export interface IRouteConfig{
  readonly path: string,
  readonly name: string,
  readonly comp: ReactElement<RouteProps>,
}

const routes: IRouteConfig[] = [
    {path: "/feature/system/menu/correct", name: "correct menu", comp: <Route path="/feature/system/menu"><Menu /></Route>},
    {path: "/feature/system/menu/error", name: "error menu", comp: <Menu />},
];

export default routes;

what I excepted is a compiler error at second line in routes, but not any. what's the right way to do that?

JSX:

comp = <Route path="/feature/system/menu"><Menu /></Route>

equals to plain javascript

comp = Route({path:"/feature/system/menu", children: Menu()});

ie, running function Route with parameter path and children , and then assigning the function return value to comp.

So, by giving comp a type, you're really typing the return value of Route , typescript doesn't know what parameter you give to it, so it can't be typed!

PS: if you want to type a function's parameter, you need to declare it in function.

export const Menu = (props:RouteProps) => {
...
}

or

export function Menu(props:RouteProps) {
...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM