microsoft / microsoft/TypeScript

Allow to specify return type of constructor

Open
#27,594 29 comments 42 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

In Discussion Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Search Terms

constructor return type

Suggestion

Add an ability to specify return type of a class constructor.
Right now the compiler produces the following error: "Type annotation cannot appear on a constructor declaration."

Use Cases

Consider this example:

interface MyInterface {
  readonly data: ReadonlyArray<string>

  add(item: string): void
  remove(item: string): void

  // ...more
}

class MyClass implements MyInterface {
  data = [] as string[]
  
  constructor(): MyInterface {} // right now it's an error

  add(item: string) {
    this.data.push(item)
  }

  // ...more
}

Current behavior:

const c = new MyClass() // typeof c == MyClass
c.data = [] // oops! no error from the compiler

Suggested behavior:

const c = new MyClass() // typeof c == MyInterface
c.data = [] // the compiler generates an error here, correct behavior

Of course, there are several ways to achieve this result (like using private constructor with factory function, or using a type converter like this:
type AsInterface<T, C> = C extends new (...args: infer A) => T ? new (...args: A) => T : never
But I think that the proposed feature is more concise

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. new expression-level syntax)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No implementation files or tests are named. Start by reviewing the constructor return-type examples and the current compiler error, then trace how new MyClass() is typed. Done means the proposed annotation is accepted, the constructed value is exposed as MyInterface, and invalid writes such as c.data = [] are rejected without changing emitted JavaScript.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.