What does the 'new' keyword before the parameter list mean in a typscript arrow function?

187 Views Asked by At

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?

1

There are 1 best solutions below

2
On BEST ANSWER

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);