4

I'm pretty new to TypeScript or even JavaScript for that matter. And I've been trying to wrap my head around an example from Microsoft on how to integrate AzureAD authentication in a react app. The example uses an HOC to provide authentication to a component. The declaration for the HOC looks like this:

function withAuthProvider<T extends React.Component<AuthComponentProps>>(
    WrappedComponent: new (props: AuthComponentProps, context?: any) => T
): React.ComponentClass {...}

Most of it is more or less clear. What puzzles me is the type of WrappedComponent. Specifically I don't understand what the new keyword does in that context.

Can anyone help me out?

Tobi
  • 5,499
  • 3
  • 31
  • 47

1 Answers1

6

It's a constructor type. It means that when you invoke it with new, you can give it a props argument and an optional context argument, and it'll construct an instance of type T.

Here's an example:

class Foo {
    private value: number;
    constructor(x: number, y: number = 1) {
        this.value = x + y;
    }
}

const foo: new (arg1: number, arg2?: number) => Foo = Foo;
// can be invoked like this (with new)
const x1: Foo = new foo(1);
const x2: Foo = new foo(1, 2);
// cannot be invoked without new
// these lines will error at both compile- and run-time
const y1: Foo = foo(1);
const y2: Foo = foo(1, 2);
Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • Thanks for your answer. Would you mind elaborating a bit on the subject? What do you mean by 'invoke with new'? The way this is invoked in the example is this: `class App extends React.Component {...} ... export default withAuthentication(App)`. Does the signature mean, that the class you pass it has to have a construction that accepts a `props: AuthComponentProps` and optionally the `context`? Is there another way to invoke that function? – Tobi Dec 13 '20 at 14:40
  • Ah I see, you meant that what is passed as param would be invoked with `new`. I thought I could do sth like `const comp = new withAuthentication(props)`. Thank you! – Tobi Dec 13 '20 at 14:50