Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't understand how get typescript work with route params #438

Closed
bezenson opened this issue Jan 23, 2023 · 4 comments · Fixed by #465
Closed

Can't understand how get typescript work with route params #438

bezenson opened this issue Jan 23, 2023 · 4 comments · Fixed by #465

Comments

@bezenson
Copy link

I created a router in a way that is explained in the description:

    <Router>
      <Products path={routePath('/:id?')} />
      <Cart path={routePath('/cart')} />
    </Router>

Products component has matches, path, url props inside.

When I am describing them in interface - I am getting error in root tsx file:

Type '{ path: string; }' is not assignable to type 'IntrinsicAttributes & ProductsProps & Readonly<Attributes & { children?: ComponentChildren; ref?: Ref | undefined; }>'.
Type '{ path: string; }' is missing the following properties from type 'ProductsProps': matches, url, idts(2322)

interface ProductsProps {
  path: string;
  matches: { id: string; };
  url: string;
  id: string;
}

const Products: FunctionComponent<ProductsProps> = (props) => {
  console.log('Products props', props);

  return <div />
};

Of course I can make props optional, but this is a hack, not a solution. When I render component inside <Route> it will always have this props.

@rschristian
Copy link
Member

Of course I can make props optional, but this is a hack, not a solution

Not really, no. This is an inherent limitation of TypeScript and type safety in general. AFAIK, TS offers no mechanism to override or extend the props of child nodes. If you say ProductProps takes specific props, then they need to be supplied or marked as optional.

However, there's sort of a workaround in the Route component, if you want to appease TS:

import { Route, Router } from 'preact-router';

function App() {
    return (
        <Router>
            <Route path={routePath('/:id?')} component={Products} />
            <Route path={routePath('/cart')} component={Cart} />
        </Router>
    );
} 

This will get rid of the error.

@bezenson
Copy link
Author

bezenson commented Feb 1, 2023

@rschristian It looks like a solution. Thank you.
Will be good to add it to README.MD

@rschristian
Copy link
Member

PRs welcome

@zlondrej
Copy link
Contributor

zlondrej commented Apr 5, 2024

@rschristian Here's a PR: #465

@rschristian rschristian linked a pull request Apr 6, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants