Skip to content

Inference fails for generic-typed constructor parameter when no explicit constructor is present #47340

Description

Bug Report

I'm trying to write a function that takes a (generic) constructor and calls it to instantiate a class. The type inference for such a function normally works fine, but if the constructor is for a generic class it fails even if the generic parameter has a default.

🔎 Search Terms

generic constructor parameter inference instanceof

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about constructor parameters

⏯ Playground Link

Playground link with relevant code

💻 Code

class Foo<K extends {} = {}> {}

function create<T>(type: new () => T): T {
    return new type();
}

let string = create(String); // has type String

let foo = create(Foo); // should have type Foo<{}>, has type unknown

🙁 Actual behavior

The foo variable has type unknown.

🙂 Expected behavior

I expected the foo variable to have type Foo<{}>.

Activity

  1. cijiugechu commented on Jan 7, 2022

    @cijiugechu

    Probably because the class Foo don't have a constructor, K didn't be consumed in the class.

  2. MartinJohns commented on Jan 7, 2022

    @MartinJohns
    Contributor

    Use this instead:

    function create<T extends new () => any>(type: T): InstanceType<T> {
        return new type();
    }

    Also, be wary of the String type. It's not assignable to string.

  3. RyanCavanaugh commented on Jan 12, 2022

    @RyanCavanaugh
    Member

    This is a bug; inserting the constructor that's "there" by default

    constructor() {}

    changes the behavior

  4. changed the title [-]Inference fails for generic-typed constructor parameter[/-] [+]Inference fails for generic-typed constructor parameter when no explicit constructor is present[/+] on Jan 12, 2022
  5. locked as resolved and limited conversation to collaborators on Oct 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptHelp WantedYou can do this

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions