Search code examples
reactjstypescriptreact-routertsc

Cannot pass props to React Router page component, TS2322


I’m fighting the typescript compiler trying to expect props in an exported component that is rendered as a React Router page. (I am using the newest version of react-router-dom, 5.2.0.

In my library code:

interface AppProps {
    baseApiUrl?: string
}
export function App({
    baseApiUrl = ''
}: AppProps): React.ReactElement<AppProps> { /* my component code */ }

In the implementation code where I'm seeing the typescript error:

export function Sandbox(): React.ReactElement {
    return (
        <BrowserRouter>
            <Switch>
                <Route path="*">
                    <App baseApiUrl="http://localhost:3000"  />
                </Route>
            </Switch>
        </BrowserRouter>
    )
}

Why is it that I am getting this typescript error?

TS2322: Type '{ baseApiUrl: string; }' is not assignable to type 'IntrinsicAttributes & AppProps'.
  Property 'baseApiUrl' does not exist on type 'IntrinsicAttributes & AppProps'.
     8 |            <Switch>
     9 |                <Route path="*">
  > 10 |                    <App baseApiUrl="http://localhost:3000"  />
       |                         ^^^^^^^^^^
    11 |                </Route>
    12 |            </Switch>
    13 |        </BrowserRouter>

Where is this IntrinsicAttributes coming from? What can I do to make the compiler happy?

I've already tried to rewrite the function signature like this:

export const App: React.FC<AppProps> = (props) => { /* my component code */ }

and got the same compiler error.


Solution

  • Answer you don't need to do anything to make the compiler happy.

    As you can see at https://codesandbox.io/s/vibrant-wood-5clyq?file=/src/App.tsx the code you shared is fine, so there must be some other code broken somehow. For example you have two things both called AppProps, and the one that generates the error is different than the one you shared. Given you didn't share a minimal reproducible example it's only a guess.

    Perhaps you could make a reproducible example by forking the sandbox I shared above?

    enter image description here