Skip to content

Feature Request: Improve type narrowing for class instances inside switch-case expressions #49188

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
5 tasks done
ScarletFlash opened this issue May 20, 2022 · 2 comments
Closed
5 tasks done
Labels
Duplicate An existing issue was already created

Comments

@ScarletFlash
Copy link

ScarletFlash commented May 20, 2022

Suggestion

πŸ” Search Terms

constructor, instanceof, switch

βœ… Viability 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. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Add type narrowing based on object constructor in switch case expressions.

πŸ“ƒ Motivating Example

Let's imagine we have 2 dedicated parts of our codebase:

  1. Objects creation
  2. Created objects handling

It may be useful to use switch case expression for handling incoming objects instead of using multiple type guards:

Using switch case
abstract class Animal {}

class Pig extends Animal {
    public oink(): void {}
}
class Dog extends Animal {
    public bark(): void {}

}
class Cow extends Animal  {
    public moo(): void {}

}

const animal: Animal = new Pig();

switch (animal.constructor) {
  case Pig: {
    animal.oink()
    break;
  }
  case Dog: {
    animal.bark()
    break;
  }
  case Cow: {
    animal.moo()
    break;
  }
  default: {
    break;
  }
}
Using type guards
abstract class Animal {}

class Pig extends Animal {
    public oink(): void {}
}
class Dog extends Animal {
    public bark(): void {}

}
class Cow extends Animal  {
    public moo(): void {}

}

const animal: Animal = new Pig();

if (animal instanceof Pig) {
    animal.oink()
}

if (animal instanceof Dog) {
    animal.bark()
}

if (animal instanceof Cow) {
    animal.moo()
}

πŸ’» Use Cases

This feature is required in event-driven architectures. Here goes a sample:

Sample
class UserInteractionHandler implements Creatable, Destroyable {
    private readonly onEventCallback: OnEventCallback = (busEvent: BusEvent) => {

        switch (busEvent.constructor) {
            case MouseClickBusEvent: {
                const { payload }: MouseClickBusEvent = busEvent;
                /** ... */
                break;
            }
            case MouseMoveBusEvent: {
                const { payload }: MouseMoveBusEvent = busEvent;
                /** ... */
                break;
            }
            case KeyDownBusEvent: {
                const { payload }: KeyDownBusEvent = busEvent;
                /** ... */
                break;
            }
            case KeyUpBusEvent: {
                const { payload }: KeyUpBusEvent = busEvent;
                /** ... */
                break;
            }
            default: {
                break;
            }
        }

    }

    constructor(private readonly eventBus){}

    public onCreate(): void {
        this.eventBus.listen(this.onEventCallback);
    }

    public onDestroy(): void {
        this.eventBus.unlisten(this.onEventCallback);
    }

}

class MouseEventsPublisher implements Creatable, Destroyable {
    private readonly clickListener: EventListener = (event: MouseEvent) => {
        this.eventBus.dispatch(new MouseClickBusEvent(event));
    }
    private readonly mouseMoveListener: EventListener = (event: MouseEvent) => {
        this.eventBus.dispatch(new MouseMoveBusEvent(event));
    }

    constructor(private readonly eventBus){}


    public onCreate(): void {
        window.addEventListener('click', this.clickListener);
        window.addEventListener('mousemove', this.mouseMoveListener);
    }

    public onDestroy(): void {
        window.removeEventListener('click', this.clickListener);
        window.removeEventListener('mousemove', this.mouseMoveListener);
    }
    
}

class KeyboardEventsPublisher implements Creatable, Destroyable {
    private readonly keyDownListener: EventListener = (event: KeyboardEvent) => {
        this.eventBus.dispatch(new KeyDownBusEvent(event));
    }
    private readonly keyUpListener: EventListener = (event: KeyboardEvent) => {
        this.eventBus.dispatch(new KeyUpBusEvent(event));
    }

    constructor(private readonly eventBus){}


    public onCreate(): void {
        window.addEventListener('keydown', this.keyDownListener);
        window.addEventListener('keyup', this.keyUpListener);
    }

    public onDestroy(): void {
        window.removeEventListener('keydown', this.keyDownListener);
        window.removeEventListener('keyup', this.keyUpListener);
    }
    
}
@MartinJohns
Copy link
Contributor

Duplicate of #16035.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label May 20, 2022
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants