Definitelytyped: react-router: `withRouter` falla con` ComponentType` comenzando en 3.6.2

Creado en 10 sept. 2019  ·  10Comentarios  ·  Fuente: DefinitelyTyped/DefinitelyTyped

Esto funcionó en 3.5.2, pero falla en 3.6.2.

strict está desactivado.

¿Es esto un error en la mecanografía o TypeScript?

Agregué pruebas fallidas para esto aquí: https://github.com/DefinitelyTyped/DefinitelyTyped/commit/f036856dfc9a7fd140f378402c102206738ec0a4.

import * as React from 'react';

// Copied from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/5db94ca7fd3570dc23588b404d7bb669a7886a8a/types/react-router/index.d.ts#L146
declare function withRouter<P, C extends React.ComponentType<P>>(
    component: C & React.ComponentType<P>,
): unknown;

declare const Component: React.ComponentType<{}>;
/*
Argument of type 'ComponentType<{}>' is not assignable to parameter of type 'ComponentClass<{}, any> | (ComponentClass<{}, any> & FunctionComponent<{}>)'.
  Type 'FunctionComponent<{}>' is not assignable to type 'ComponentClass<{}, any> | (ComponentClass<{}, any> & FunctionComponent<{}>)'.
    Type 'FunctionComponent<{}>' is not assignable to type 'ComponentClass<{}, any> & FunctionComponent<{}>'.
      Type 'FunctionComponent<{}>' is not assignable to type 'ComponentClass<{}, any>'.
        Type 'FunctionComponent<{}>' provides no match for the signature 'new (props: {}, context?: any): Component<{}, any, any>'.
*/
withRouter(Component);

Si sabe cómo solucionar el problema, realice una solicitud de extracción.

  • [x] Intenté usar el paquete @types/xxxx y tuve problemas.
  • [x] Intenté usar la última versión estable de tsc. https://www.npmjs.com/package/typescript
  • [x] Tengo una pregunta que no es apropiada para StackOverflow . (Haga las preguntas correspondientes allí).
  • [x] [Mencione] (https://github.com/blog/821-mention-somebody-they-re-notified) a los autores (consulte Definitions by: en index.d.ts ) para que puedan responder.

    • Autores: @ sergey-buturlakin @ mrk21 @ vasek17 @ngbrown @awendland @KostyaEsmukov @johnnyreilly @LKay @DovydasNavickas @ huy-nguyen @grmiade @DaIgeb @egorshulga @rraina @ preleyentsSslon @ t49tran @ eps1

Si no menciona a los autores, se ignorará el problema.

Bug

Comentario más útil

Sigo viendo problemas incluso después de esta solución. El mensaje de error es algo como

 Argument of type '({ myProp, history }: RouteComponentProps<{}, StaticContext, any> & { myProp: boolean; }) => Element' is not assignable to parameter of type 'ComponentType<RouteComponentProps<{}, StaticContext, any>>'.
  Type '({ myProp, history }: RouteComponentProps<{}, StaticContext, any> & { myProp: boolean; }) => Element' is not assignable to type 'FunctionComponent<RouteComponentProps<{}, StaticContext, any>>'.
    Types of parameters '__0' and 'props' are incompatible.
      Type 'PropsWithChildren<RouteComponentProps<{}, StaticContext, any>>' is not assignable to type 'RouteComponentProps<{}, StaticContext, any> & { myProp: boolean; }'.
        Property 'myProp' is missing in type 'RouteComponentProps<{}, StaticContext, any> & { children?: ReactNode; }' but required in type '{ myProp: boolean; }'.

con el componente definido como

import { RouteComponentProps, withRouter } from "react-router-dom";

interface Props extends RouteComponentProps {
  myProp: boolean;
}

const Component = ({ myProp, match }: Props) => null

export default withRouter(Component);

Estoy usando

typescript: 3.6.3
@types/react-router: 5.0.4

Todos 10 comentarios

No tendré tiempo para profundizar en esto. Creo que deberíamos eliminar cualquier uso de ComponentType y usar funciones simples con accesorios explícitos con respecto a ref y children . ComponentType siempre fue un poco problemático debido a la unión. Si no creaba errores, producía uniones muy grandes con otros hocs. Los consumidores de bibliotecas no deberían tocar las estáticas de todos modos, por lo que perderlas no debería ser un problema.

Tengo el mismo problema. Ya se informó sobre el repositorio react-router (https://github.com/ReactTraining/react-router/issues/6906) pero fue redirigido aquí.

Sigo viendo problemas incluso después de esta solución. El mensaje de error es algo como

 Argument of type '({ myProp, history }: RouteComponentProps<{}, StaticContext, any> & { myProp: boolean; }) => Element' is not assignable to parameter of type 'ComponentType<RouteComponentProps<{}, StaticContext, any>>'.
  Type '({ myProp, history }: RouteComponentProps<{}, StaticContext, any> & { myProp: boolean; }) => Element' is not assignable to type 'FunctionComponent<RouteComponentProps<{}, StaticContext, any>>'.
    Types of parameters '__0' and 'props' are incompatible.
      Type 'PropsWithChildren<RouteComponentProps<{}, StaticContext, any>>' is not assignable to type 'RouteComponentProps<{}, StaticContext, any> & { myProp: boolean; }'.
        Property 'myProp' is missing in type 'RouteComponentProps<{}, StaticContext, any> & { children?: ReactNode; }' but required in type '{ myProp: boolean; }'.

con el componente definido como

import { RouteComponentProps, withRouter } from "react-router-dom";

interface Props extends RouteComponentProps {
  myProp: boolean;
}

const Component = ({ myProp, match }: Props) => null

export default withRouter(Component);

Estoy usando

typescript: 3.6.3
@types/react-router: 5.0.4

@ karol-majewski Estoy en TS 3.6.3 y la última versión @types/react-router: 5.0.4 está rompiendo, mientras que volver a la anterior está bien.

export function withRouter<P extends RouteComponentProps<any>, C extends React.ComponentType<P>>(
  component: C & React.ComponentType<P>,
): React.ComponentClass<Omit<P, keyof RouteComponentProps<any>> & WithRouterProps<C>> & WithRouterStatics<C>;

Animo a todos a abrir nuevos números. Si solucionamos su problema particular, no tiene forma de ser notificado si solo comenta en un hilo cerrado. El patio de juegos mecanografiado ahora permite configurar la versión ts + config y puede descargar definiciones de tipo. Incluir un enlace en un número nuevo ayuda mucho a los mantenedores. Gracias: reza:

Parece que esto solo se lanza con strictFunctionTypes y tengo una solución en mente. Veremos si funciona.

@sandersn ¿Podemos volver a abrir esto ya que se revirtió la corrección ?

IIRC, @ eps1lon descubrió que esto se debe a un error de TypeScript: https://github.com/microsoft/TypeScript/issues/33490

La solución vendrá en: https://github.com/microsoft/TypeScript/pull/34607.

Funciona bien con la versión nocturna. Enlace de juegos

Mecanografiar es una pérdida de tiempo, he pasado horas tratando de resolver este estúpido error y nada, así que si el mecanografiado se hace para hacer la vida más fácil, definitivamente no está haciendo el trabajo, lleno de errores y errores.

Este problema se solucionó en TS 3.7. Clausura.

¿Fue útil esta página
0 / 5 - 0 calificaciones