Search code examples
typescripttypescript-genericsreact-typescript

What is this syntax in typescript?


    type JSXElementConstructor<P> =
        | ((props: P) => ReactElement<any, any> | null)
        | (new (props: P) => Component<any, any>);       => What is this?

What is the new part?


Solution

  • ((props: P) => ReactElement<any, any> | null) describes a plain function that, when called, returns a ReactElement.

    (new (props: P) => Component<any, any>) describes a class that, when called with new, returns a Component - hence the new.

    They're not interchangeable . The union lets JSXElementConstructor account for both functional components and class components.

    For a simple example outside of React of a newable that's assignable to new () =>:

    type X = (new () => { getName: () => string });
    class Person {
        #name = 'foo';
        getName() {
            return this.#name;
        }
    }
    
    const P: X = Person;