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