2017-11-13 1 views
2

Ich versuche matchPath zu verwenden, um eine Route param aus dem übergeordneten Container zu extrahieren, wie in https://stackoverflow.com/a/45492498/3574819Wie Typoskript Typen für matchPath Rückgabewert

const topicMatch = matchPath(history.location.pathname, { path: '/:topic' }); 

Als ich console.log(topicMatch.params), hat das Objekt den topic Schlüsselsatz einstellen aber wenn ich versuche, topicMatch.params.topic zuzugreifen bekomme ich folgende Fehlermeldung:

error TS2339: Property 'topic' does not exist on type '{}'.

const RouterApp = withRouter<{}>(
    class App extends React.Component<RouteComponentProps<{}>, AuthState> { 
     render() { 
      const { history } = this.props;  
      const topicMatch = matchPath(history.location.pathname, { path: '/:topic' }); 

      if (topicMatch) { 
       console.log(topicMatch.params); // has topic key 
       console.log(topicMatch.params.topic); // causes compile error 
      } 

      return (
       <div className="App"> 
        <div className="App-header"> 
         <img src={logo} className="App-logo" alt="logo"/> 
         <h2>Welcome to React</h2> 
        </div> 
       </div> 
      ); 
     } 
    } 
); 

Antwort

2

matchPath ist eine parametrisierte func Diese Anwendung nimmt den generischen Typ <P> an und gibt eine Übereinstimmung mit match<P> zurück. Es liegt an Ihnen, P zu definieren; Ansonsten bin ich mir nicht sicher, wie TypeScript den Rückgabetyp bestimmt.

matchPath<{topic: "string"}>(...) 

Sie könnten auch Ihren eigenen Typ erstellen, wenn Sie möchten, z.

interface RouteParams { 
    topic: string; 
} 

und dann tun Sie .