react-router 路由参数上的类型安全可能吗?
Type safety on react-router Route params possible?
是否可以安全地访问 react-router 2.0 路由属性 w/TypeScript?例如:
<Router>
<Route path="/" component={App}>
<Route path="screenOne" header="Screen One" component={ScreenOne}/>
</Route>
</Router>
可以通过 'this.props.route.header' 访问 screenOne 路由的 header 值,但似乎不可能既设置它又使用 TypeScript 访问它而不收到 [=21] 的警告=] 既不存在于路由端,也不存在于访问 属性 的组件内部。我查看了 http://definitelytyped.org/ and https://github.com/typings/typings
中的两个定义文件
根据 https://whosebug.com/users/2225281/aaron 的评论,您似乎可以做到这一点,但使用 Typings 中的定义有点愚蠢。也许有人可以对此进行扩展以进行改进或有更好的主意,但这是我到目前为止在 routes.tsx 文件或类似文件中所做的假设:
//Create a type to limit duplication and help w/refactoring
type Header = string;
//Interface for the injected props. Used by component via 'this.props.route.header'
export interface HeaderRouteInjectedProps extends IInjectedProps {
route?: IRoute & {
header: Header
}
}
//Interface and class to create a new Route type 'HeaderRoute' that requires a header property
interface HeaderRouteProps extends IRouteProps {
header: Header
}
class HeaderRoute extends React.Component<HeaderRouteProps, {}> { }
是否可以安全地访问 react-router 2.0 路由属性 w/TypeScript?例如:
<Router>
<Route path="/" component={App}>
<Route path="screenOne" header="Screen One" component={ScreenOne}/>
</Route>
</Router>
可以通过 'this.props.route.header' 访问 screenOne 路由的 header 值,但似乎不可能既设置它又使用 TypeScript 访问它而不收到 [=21] 的警告=] 既不存在于路由端,也不存在于访问 属性 的组件内部。我查看了 http://definitelytyped.org/ and https://github.com/typings/typings
中的两个定义文件根据 https://whosebug.com/users/2225281/aaron 的评论,您似乎可以做到这一点,但使用 Typings 中的定义有点愚蠢。也许有人可以对此进行扩展以进行改进或有更好的主意,但这是我到目前为止在 routes.tsx 文件或类似文件中所做的假设:
//Create a type to limit duplication and help w/refactoring
type Header = string;
//Interface for the injected props. Used by component via 'this.props.route.header'
export interface HeaderRouteInjectedProps extends IInjectedProps {
route?: IRoute & {
header: Header
}
}
//Interface and class to create a new Route type 'HeaderRoute' that requires a header property
interface HeaderRouteProps extends IRouteProps {
header: Header
}
class HeaderRoute extends React.Component<HeaderRouteProps, {}> { }