microsoft / microsoft/TypeScript
Allow intersection type guards for multiple parameters
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.4k
- Ø Merge
- 1 T. 19 Std.
- Gemergte PRs (30 T.)
- 117
Beschreibung
Search Terms
type guard multiple parameters
Suggestion
I'd like to write a type guard that takes two parameters and changes the type of both of them.
Use Cases
My specific use case is to try to make the following pattern (somewhat) more type-safe:
class Foo<TFeature, TOther> {
// If featureCtor is null, TFeature will never be used.
constructor(private readonly featureCtor: { new(): TFeature } | null) { }
isFeature(thing: any): thing is TFeature {
return !!this.featureCtor && thing instanceof this.featureCtor;
}
bar(thing: TFeature|TOther) {
if (this.isFeature(thing)) {
// Type guard should prove that this.featureCtor is not null
new this.featureCtor();
} else {
// Type guard should prove this
const x: TOther = thing;
}
}
}
Examples
isFeature(thing: any, ctor: { new(): TFeature } | null): (thing is TFeature)&(ctor is { new(): TFeature }) {
return !!this.featureCtor && thing instanceof this.featureCtor;
}
It would be even nicer to allow type guards to operate on readonly fields, so I wouldn't need to pass this.featureCtor as a parameter.
I also tried
constructor(private readonly featureCtor: TFeature extends never ? null : { new(): TFeature }) { }
But that didn't work.
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
Beginnen Sie mit der Untersuchung des Type-Guard-Beispiels der Ausgabe mit zwei Parametern und des gewünschten Verhaltens für die Eingrenzung beider Parameter, einschließlich readonly-Feldern. In der Ausgabe wird keine Quelldatei und kein Test genannt; als abgeschlossen würde gelten, wenn intersection type guards unterstützt werden, ohne das erzeugte JavaScript oder das bestehende Laufzeitverhalten 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
- 25/100