Skip to content

Allow intersection type guards for multiple parameters #26916

Open
@SLaks

Description

@SLaks

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions