Búsqueda de sitios web

reactjs - Typescript causando errores con React Router Dom


Estoy trabajando en un proyecto de Angular en el que estamos en las primeras fases de implementación de React (eventualmente reescribiendo la aplicación completamente en React, pero aún no ha sido aprobado). El proyecto también utiliza Typescript, de donde proviene mi problema. Estoy tratando de usar React-Router-Dom para navegar entre las páginas dentro de la aplicación, pero Typescript sigue lanzando errores similares a los siguientes. He actualizado todo a las versiones más recientes, pero aún recibo los mismos errores. También he desinstalado y reinstalado Typescript, como he visto en otros posts. ¿Alguien podría ayudarme a resolver esto? A estas alturas, no me importa si la solución es hacer que Typescript ignore React-Router-Dom por completo, simplemente estoy cansado de este problema.

ERROR in ../node_modules/@remix-run/router/dist/utils.d.ts:161:61 - error TS1110: Type expected.

161 declare type _PathParam<Path extends string> = Path extends `${infer L}/${infer R}` ? _PathParam<L> | _PathParam<R> : Path extends `:${infer Param}` ? Param : never;
                                                                ~~~
../node_modules/@remix-run/router/dist/utils.d.ts:161:70 - error TS1005: '}' expected.

161 declare type _PathParam<Path extends string> = Path extends `${infer L}/${infer R}` ? _PathParam<L> | _PathParam<R> : Path extends `:${infer Param}` ? Param : never;
                                                                         ~
../node_modules/@remix-run/router/dist/utils.d.ts:161:71 - error TS1128: Declaration or statement expected.

161 declare type _PathParam<Path extends string> = Path extends `${infer L}/${infer R}` ? _PathParam<L> | _PathParam<R> : Path extends `:${infer Param}` ? Param : never;
                                                                          ~
../node_modules/@remix-run/router/dist/utils.d.ts:161:73 - error TS1161: Unterminated regular expression literal.

161 declare type _PathParam<Path extends string> = Path extends `${infer L}/${infer R}` ? _PathParam<L> | _PathParam<R> : Path extends `:${infer Param}` ? Param : never;

../node_modules/@remix-run/router/dist/utils.d.ts:171:85 - error TS1110: Type expected.

171 declare type PathParam<Path extends string> = Path extends "*" ? "*" : Path extends `${infer Rest}/*` ? "*" | _PathParam<Rest> : _PathParam<Path>;       
                                                                                        ~~~
../node_modules/@remix-run/router/dist/utils.d.ts:171:94 - error TS1005: '}' expected.

171 declare type PathParam<Path extends string> = Path extends "*" ? "*" : Path extends `${infer Rest}/*` ? "*" | _PathParam<Rest> : _PathParam<Path>;       
                                                                                                 ~~~~
../node_modules/@remix-run/router/dist/utils.d.ts:171:98 - error TS1128: Declaration or statement expected.

171 declare type PathParam<Path extends string> = Path extends "*" ? "*" : Path extends `${infer Rest}/*` ? "*" | _PathParam<Rest> : _PathParam<Path>;       
                                                                                                     ~
../node_modules/@remix-run/router/dist/router.d.ts:15:5 - error TS1131: Property or signature expected.

15     get basename(): RouterInit["basename"];
       ~~~
../node_modules/@remix-run/router/dist/router.d.ts:15:9 - error TS1005: ';' expected.

15     get basename(): RouterInit["basename"];
           ~~~~~~~~
../node_modules/@remix-run/router/dist/router.d.ts:15:19 - error TS1005: ';' expected.

15     get basename(): RouterInit["basename"];
                     ~
../node_modules/@remix-run/router/dist/router.d.ts:22:9 - error TS1005: ';' expected.

22     get state(): RouterState;
           ~~~~~
../node_modules/@remix-run/router/dist/router.d.ts:22:16 - error TS1005: ';' expected.

22     get state(): RouterState;
                  ~
../node_modules/@remix-run/router/dist/router.d.ts:29:9 - error TS1005: ';' expected.

29     get routes(): AgnosticDataRouteObject[];
           ~~~~~~
../node_modules/@remix-run/router/dist/router.d.ts:29:17 - error TS1005: ';' expected.

29     get routes(): AgnosticDataRouteObject[];
                   ~
../node_modules/@remix-run/router/dist/router.d.ts:29:43 - error TS1011: An element access expression should take an argument.

29     get routes(): AgnosticDataRouteObject[];

../node_modules/@remix-run/router/dist/router.d.ts:38:17 - error TS1005: ';' expected.

38     initialize(): Router;
                   ~
../node_modules/@remix-run/router/dist/router.d.ts:47:17 - error TS1005: ',' expected.

47     subscribe(fn: RouterSubscriber): () => void;
                   ~
../node_modules/@remix-run/router/dist/router.d.ts:47:36 - error TS1005: ';' expected.

47     subscribe(fn: RouterSubscriber): () => void;
                                      ~
../node_modules/@remix-run/router/dist/router.d.ts:47:48 - error TS1109: Expression expected.

47     subscribe(fn: RouterSubscriber): () => void;
                                                  ~
../node_modules/@remix-run/router/dist/router.d.ts:59:49 - error TS1005: ',' expected.

59     enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;
                                                   ~
../node_modules/@remix-run/router/dist/router.d.ts:59:73 - error TS1109: Expression expected.

59     enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;
                                                                           ~
../node_modules/@remix-run/router/dist/router.d.ts:59:92 - error TS1005: ',' expected.

59     enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;
                                                                                              ~
../node_modules/@remix-run/router/dist/router.d.ts:59:128 - error TS1109: Expression expected.

59     enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;
                                                                                                                                  ~
../node_modules/@remix-run/router/dist/router.d.ts:59:162 - error TS1005: ';' expected.

59     enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;

       ~
../node_modules/@remix-run/router/dist/router.d.ts:59:174 - error TS1109: Expression expected.

59     enableScrollRestoration(savedScrollPositions: Record<string, number>, getScrollPosition: GetScrollPositionFunction, getKey?: GetScrollRestorationKeyFunction): () => void;

                   ~
../node_modules/@remix-run/router/dist/router.d.ts:67:16 - error TS1005: ',' expected.

67     navigate(to: number): void;
                  ~
../node_modules/@remix-run/router/dist/router.d.ts:67:25 - error TS1005: ';' expected.

67     navigate(to: number): void;
                           ~
../node_modules/@remix-run/router/dist/router.d.ts:67:31 - error TS1109: Expression expected.

67     navigate(to: number): void;
                                 ~
../node_modules/@remix-run/router/dist/router.d.ts:73:16 - error TS1005: ',' expected.

73     navigate(to: To, opts?: RouterNavigateOptions): void;
                  ~
../node_modules/@remix-run/router/dist/router.d.ts:73:27 - error TS1109: Expression expected.

73     navigate(to: To, opts?: RouterNavigateOptions): void;
                             ~
../node_modules/@remix-run/router/dist/router.d.ts:73:51 - error TS1005: ';' expected.

73     navigate(to: To, opts?: RouterNavigateOptions): void;
                                                     ~
../node_modules/@remix-run/router/dist/router.d.ts:73:57 - error TS1109: Expression expected.

73     navigate(to: To, opts?: RouterNavigateOptions): void;
                                                           ~
../node_modules/@remix-run/router/dist/router.d.ts:85:14 - error TS1005: ',' expected.

85     fetch(key: string, routeId: string, href: string, opts?: RouterNavigateOptions): void;
                ~
../node_modules/@remix-run/router/dist/router.d.ts:85:31 - error TS1005: ',' expected.

85     fetch(key: string, routeId: string, href: string, opts?: RouterNavigateOptions): void;
                                 ~
../node_modules/@remix-run/router/dist/router.d.ts:85:45 - error TS1005: ',' expected.

85     fetch(key: string, routeId: string, href: string, opts?: RouterNavigateOptions): void;
                                               ~
../node_modules/@remix-run/router/dist/router.d.ts:85:60 - error TS1109: Expression expected.

85     fetch(key: string, routeId: string, href: string, opts?: RouterNavigateOptions): void;
                                                              ~
../node_modules/@remix-run/router/dist/router.d.ts:85:84 - error TS1005: ';' expected.

85     fetch(key: string, routeId: string, href: string, opts?: RouterNavigateOptions): void;
                                                                                      ~
../node_modules/@remix-run/router/dist/router.d.ts:85:90 - error TS1109: Expression expected.

85     fetch(key: string, routeId: string, href: string, opts?: RouterNavigateOptions): void;
                                                                                            ~
../node_modules/@remix-run/router/dist/router.d.ts:92:17 - error TS1005: ';' expected.

92     revalidate(): void;
                   ~
../node_modules/@remix-run/router/dist/router.d.ts:92:23 - error TS1109: Expression expected.

92     revalidate(): void;
                         ~
../node_modules/@remix-run/router/dist/router.d.ts:100:24 - error TS1005: ',' expected.

100     createHref(location: Location | URL): string;
                           ~
../node_modules/@remix-run/router/dist/router.d.ts:100:41 - error TS1005: ';' expected.

100     createHref(location: Location | URL): string;
                                            ~
../node_modules/@remix-run/router/dist/router.d.ts:109:22 - error TS1005: ',' expected.

109     encodeLocation(to: To): Path;
                         ~
../node_modules/@remix-run/router/dist/router.d.ts:109:27 - error TS1005: ';' expected.

109     encodeLocation(to: To): Path;
                              ~
../node_modules/@remix-run/router/dist/router.d.ts:117:22 - error TS1005: ';' expected.

117     getFetcher<TData = any>(key?: string): Fetcher<TData>;
                         ~
../node_modules/@remix-run/router/dist/router.d.ts:117:33 - error TS1109: Expression expected.

117     getFetcher<TData = any>(key?: string): Fetcher<TData>;
                                    ~
../node_modules/@remix-run/router/dist/router.d.ts:117:42 - error TS1005: ';' expected.

117     getFetcher<TData = any>(key?: string): Fetcher<TData>;
                                             ~
../node_modules/@remix-run/router/dist/router.d.ts:117:58 - error TS1005: '(' expected.

117     getFetcher<TData = any>(key?: string): Fetcher<TData>;
                                                             ~
../node_modules/@remix-run/router/dist/router.d.ts:125:23 - error TS1109: Expression expected.

125     deleteFetcher(key?: string): void;
                          ~
../node_modules/@remix-run/router/dist/router.d.ts:125:32 - error TS1005: ';' expected.

125     deleteFetcher(key?: string): void;
                                   ~
../node_modules/@remix-run/router/dist/router.d.ts:125:38 - error TS1109: Expression expected.

125     deleteFetcher(key?: string): void;
                                         ~
../node_modules/@remix-run/router/dist/router.d.ts:132:14 - error TS1005: ';' expected.

132     dispose(): void;
                 ~
../node_modules/@remix-run/router/dist/router.d.ts:132:20 - error TS1109: Expression expected.

132     dispose(): void;
                       ~
../node_modules/@remix-run/router/dist/router.d.ts:139:60 - error TS1005: '(' expected.

139     _internalFetchControllers: Map<string, AbortController>;
                                                               ~
../node_modules/@remix-run/router/dist/router.d.ts:146:56 - error TS1005: '(' expected.

146     _internalActiveDeferreds: Map<string, DeferredData>;
                                                           ~
../node_modules/@remix-run/router/dist/router.d.ts:147:1 - error TS1128: Declaration or statement expected.

147 }
    ~
 

maintain.tsx

// Material-UI Imports
import { Box } from '@material-ui/core';
import { createStyles, makeStyles, Theme } from '@material-ui/core/styles';
// React Imports
import * as React from 'react';
import {BrowserRouter, Route, Routes} from 'react-router-dom';
// React Component Imports
import Departments from '../../../react-components/maintain-pages/departments';
import Equipment from '../../../react-components/maintain-pages/equipment';
import Locations from '../../../react-components/maintain-pages/locations';
import Ltm from '../../../react-components/maintain-pages/ltm';
import Matrix from '../../../react-components/maintain-pages/matrix';
import { NavBar } from '../../../react-components/navbar/NavBar';

const Maintain = () => {
  const classes = useStyles();

  return(
    <BrowserRouter>
      <Box className={classes.root} sx={{margin: '24px 0px 0px 24px'}}>
        <h1>Maintain</h1>

        <NavBar/>
        <Routes>
           <Route path='/' element='' />  
           <Route path='/ltm' element={<Ltm />}/>
           <Route path='/matrix' element={<Matrix />}/>
           <Route path='/equipment' element={<Equipment />}/>
           <Route path='/departments' element={<Departments />}/>
           <Route path='/locations' element={<Locations />}/>
        </Routes>

      </Box>
    </BrowserRouter>
  );
};

export default Maintain;

NavBar.tsx

import * as React from 'react';
import { NavLink } from 'react-router-dom';
import './NavBarStyling.css';

// NavLinks
const menuItems = [
    {id: 1, label: 'LTM', path: '/ltm'},
    {id: 2, label: 'Matrix', path: '/matrix'},
    {id: 3, label: 'Equipment', path: '/equipment'},
    {id: 4, label: 'Departments', path: '/departments'},
    {id: 5, label: 'Locations', path: '/locations'},
];

// tslint:disable: no-shadowed-variable
export const NavBar = () => {
    return(
        <nav className='nav'>
            <ul>
                {menuItems.map(menuItems => (
                    <li key={menuItems.id} >
                        <NavLink to={menuItems.path} >
                            {menuItems.label}
                        </NavLink>
                    </li>
                ))}
            </ul>
        </nav>
    );
};

package.json

{
  "dependencies": {
    "@material-ui/core": "^4.12.4",
    "@types/react-router": "^5.1.20",
    "@types/reactstrap": "^8.7.2",
    "axios": "^0.27.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.6.2"
  },
  "devDependencies": {
    "@babel/preset-flow": "^7.18.6",
    "@types/node": "^18.11.18",
    "@types/react": "^18.0.26",
    "@types/react-dom": "^18.0.10",
    "flow-babel-webpack-plugin": "^1.1.1",
    "tslib": "^2.4.1",
    "typescript": "^4.9.4"
  }
}

Respuesta #1

Tienes [email  instalado. RRDv6 está escrito completamente en Typescript. No hay necesidad de usar los typings de @types/react-router-dom como dependencia de desarrollo.

Elimina @types/react-router-dom del proyecto con cualquiera de los siguientes comandos ejecutados desde el directorio raíz del proyecto.

npm uninstall --save-dev @types/react-router
npm uninstall --save-dev @types/react-router-dom
npm un -D @types/react-router
npm un -D @types/react-router-dom

Esto elimina la dependencia de desarrollo y actualiza el archivo package.json.

También asegúrate de que estás usando la misma versión de react y react-dom... estas dos librerías siempre se usan de manera sincronizada.

npm i -S react@18 react-dom@18

Busca e instala los @types/react y @types/react-dom apropiados si es necesario.