microsoft / microsoft/TypeScript
Allow intersection type guards for multiple parameters
Nessuno ha ancora preso questa issue.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.3k
- Merge medio
- 2g 4h
- PR unite (30g)
- 132
Descrizione
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)
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia esaminando l'esempio di type guard dell'issue con due parametri e il comportamento richiesto per restringere entrambi i parametri, inclusi i campi readonly. Nell'issue non sono indicati file sorgente né test; il lavoro sarebbe considerato completato supportando gli intersection type guards senza modificare il JavaScript emesso né il comportamento esistente a runtime.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- typescript
- Ambito
- compilers
- Tipo di issue
- Funzionalità
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 25/100