Skip to content

Constructor type inference #2893

Closed
@mattjohnsonpint

Description

@mattjohnsonpint

Feature suggestion

Consider a generic class, such as:

class Foo<T> {
  constructor(public value: T) {}
}

This works:

const foo = new Foo<string>("abc");

But this does not, currently:

const foo = new Foo("abc");

It fails with:

ERROR TS2558: Expected 1 type arguments, but got 0.
   :
 5 │ const foo = new Foo("abc");
   │             ~~~~~~~~~~~~~~
   └─ in assembly/index.ts(5,13)

I would expect type inference to work on constructors, the same as it presently does for functions. Consider that this does work:

function createFoo<T>(value: T): Foo<T> {
  return new Foo(value);
}

const foo = createFoo("abc");

And type inference on static methods works too:

class Foo<T> {
  constructor(public value: T) {}

  static create<T>(value: T): Foo<T> {
    return new Foo(value);
  }
}

const foo = Foo.create("abc");

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions