TanStack / router

🤖 Fully typesafe Router for React (and friends) w/ built-in caching, 1st class search-param APIs, client-side cache integration and isomorphic rendering.
https://tanstack.com/router
MIT License
7.79k stars 571 forks source link

Using a variable as "to" in a <Link> gives typescript error #570

Closed mathewcst closed 1 year ago

mathewcst commented 1 year ago

Describe the bug

I'm using a map to define my website navigation. Passing gives me a typescript error.

Example code:

const Menu = () => {
    const menu = [
        {
            name: 'Home',
            path: '/',
        },
        {
            name: 'About',
            path: '/about',
        }
    ]

    return (
        <nav>
            <ul>
                {menu.map((item) => (
                    <li key={item.path}>
                        <Link
                            to={item.path}
                        >
                            {item.name}
                        </Link>
                    </li>
                ))}
            </ul>
        </nav>
    )
}

The error:

Property 'search' is missing in type '{ children: (string | Element)[]; to: string; className: string; activeProps: { className: string; }; }' but required in type '{ search: SearchReducer<Partial<{}>, Partial<{}> & Partial<{}> & Omit<never, never>>; }'.ts(2741)
index.d.ts(602, 5): 'search' is declared here.

Your Example Website or App

https://stackblitz.com/edit/github-uj82gk?file=src/main.tsx

Steps to Reproduce the Bug or Issue

  1. React project
  2. Add Tanstack Router
  3. Create a array for your links
  4. Map through array and render a component for each item

Expected behavior

To be able to use inside a map passing a variable as "to"

Screenshots or Videos

No response

Platform

Additional context

No response

pawelblaszczyk5 commented 1 year ago

Would casting the array with routes as const solve the issue?

mathewcst commented 1 year ago

Yes, casting the array as const removes the warning, but feels weird to do so tbh.

pawelblaszczyk5 commented 1 year ago

It makes sense if you think about it 😄 In the current form the path property type is just a string. You can just do menu[0].path = 'foobar'. This would result in TS error so TS doesn't allow you to use this variable as a Link props, because Link in Tanstack Router is supposed to be typesafe. You can either mark it as const which prevent mutations at all or add type declaration that will make sure that you can't assign incorrect path value here.

mathewcst commented 1 year ago

Your explanation makes total sense. Thank you so much for taking the time to do so. Sorry if this was as dumb question 😅. Gonna close the issue now.

pawelblaszczyk5 commented 1 year ago

It wasn't dumb at all and I'm happy to help!