microsoft / microsoft/TypeScript
Allow intersection type guards for multiple parameters
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.3k
- Avg merge
- 2d 4h
- Merged PRs (30d)
- 132
Description
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)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by examining the issue's two-parameter type-guard example and the requested behavior for narrowing both parameters, including readonly fields. No source file or test is named in the issue; done would mean supporting intersection type guards without changing emitted JavaScript or existing runtime behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100