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:
classFoo<TFeature,TOther>{// If featureCtor is null, TFeature will never be used.constructor(privatereadonlyfeatureCtor: {new(): TFeature}|null){}isFeature(thing: any): thing is TFeature{return!!this.featureCtor&&thinginstanceofthis.featureCtor;}bar(thing: TFeature|TOther){if(this.isFeature(thing)){// Type guard should prove that this.featureCtor is not nullnewthis.featureCtor();}else{// Type guard should prove thisconstx: 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:
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:
Examples
It would be even nicer to allow type guards to operate on readonly fields, so I wouldn't need to pass
this.featureCtoras a parameter.I also tried
But that didn't work.
Checklist
My suggestion meets these guidelines: