microsoft / microsoft/TypeScript
Allow to specify return type of constructor
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.3k
- Ø Merge
- 2 T. 4 Std.
- Gemergte PRs (30 T.)
- 132
Beschreibung
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)
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Es sind keine Implementierungsdateien oder Tests genannt. Beginne damit, die Beispiele für Rückgabetypen von Konstruktoren und den aktuellen Compilerfehler zu prüfen, und verfolge anschließend, wie new MyClass() typisiert wird. Erledigt ist die Aufgabe, wenn die vorgeschlagene Annotation akzeptiert wird, der konstruierte Wert als MyInterface offengelegt wird und ungültige Schreibvorgänge wie c.data = [] abgelehnt werden, ohne das erzeugte JavaScript zu ändern.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- typescript
- Bereich
- compilers
- Issue-Typ
- Feature
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 30/100