Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
Type annotation for React Higher Order Component using TypeScript

I am writing a Higher Order Component for my React project using Typescript which is basically a function accepts a React component as an argument and return a new component that wraps around it.

Yet as it works as expected, TS is complaining that "Return type of exported function has or is using private name "Anonymous class".

Function in question:

export default function wrapperFunc <Props, State> (
    WrappedComponent: typeof React.Component,
) {
    return class extends React.Component<Props & State, {}> {
        public render() {
            return <WrappedComponent {...this.props} {...this.state} />;
        }
    };
}

The error is reasonable as the returning class of wrapper function is not exported and other module imports this function has no way of knowing what the return value would be. But I cannot declare the return class outside of this function as it requires to wrap a component pass to the outer function.

A trial with explicitly specifying return type typeof React.Component like below do suppress this error.

Function in question with explicit return type:

export default function wrapperFunc <Props, State> (
    WrappedComponent: typeof React.Component,
): typeof React.Component {                     // <== Added this
    return class extends React.Component<Props & State, {}> {
        public render() {
            return <WrappedComponent {...this.props} {...this.state} />;
        }
    };
}

However, I am not certain about validity of this approach. Is it considered a right approach for tackling this particular error in TypeScript? (Or am I creating unintended side effects elsewhere? Or any better way of doing such?)

(Edit) Change quoted code as per Daniel's suggestion.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Type annotation for React Higher Order Component using TypeScript

The return type typeof React.Component is truthful, but not very helpful for users of the wrapped component. It discards information about what props the component accepts.

The React typings provide a handy type for this purpose, React.ComponentClass. It’s the type of a class, rather than the type of the component created from that class:

React.ComponentClass<Props>

(Note that the state type isn’t mentioned as it’s an internal detail).

In your case:

export default function wrapperFunc <Props, State, CompState> (
    WrappedComponent: typeof React.Component,
): React.ComponentClass<Props & State> {
    return class extends React.Component<Props & State, CompState> {
        public render() {
            return <WrappedComponent {...this.props} {...this.state} />;
        }
    };
}

However, you’re doing the same thing with the WrappedComponent parameter. Based on how you’re using it inside render, I’m guessing that it should also be declared:

WrappedComponent: React.ComponentClass<Props & State>,

But this is wild guess as I assume this is not the complete function (CompState isn’t used, and Props & State may as well be a single type parameter as it always appears in that combination).

over 4 years ago · Santiago Trujillo Relatório

0

A more appropriate type for the input parameter would be React.ComponentType, since it handles stateless components too.

type ComponentType<P = {}> = ComponentClass<P> | StatelessComponent<P>

Following is an example clarifying its usage.

import * as React from 'react';

export default function <P = {}>(
  WrappedComponent: React.ComponentType<P>
): React.ComponentClass<P> {
  return class extends React.Component<P> {
    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
}  
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda