Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type safety on react-router Route params possible?

Is it possible to access react-router 2.0 Route properties w/TypeScript in a safe manner? For example:

<Router>
  <Route path="/" component={App}>
    <Route path="screenOne" header="Screen One" component={ScreenOne}/>
  </Route>
</Router>

The header value of the screenOne Route can be accessed via 'this.props.route.header', but it doesn't seem possible to both set that and access it using TypeScript without getting warnings that the property doesn't exist on either the Route side or inside the component that accesses the property. I've looked through both the definition files in http://definitelytyped.org/ and https://github.com/typings/typings

like image 691
TS Wannabe Avatar asked Mar 04 '16 14:03

TS Wannabe


1 Answers

Based on comment from https://stackoverflow.com/users/2225281/aaron it seems you can do this, but it's a slightly goofy using the definitions from Typings. Maybe someone can expand on this for improvement or has a better idea, but this is what I have so far assuming inside the routes.tsx file or similar:

//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, {}> { }
like image 136
TS Wannabe Avatar answered Oct 01 '22 15:10

TS Wannabe