Skip to content

Type narrow with switch(obj.constructor)Β #54404

Closed
@pauldraper

Description

@pauldraper

Suggestion

πŸ” Search Terms

constructor property, type narrowing

βœ… 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

I would like the .constructor property to narrow the type in a switch statement.

πŸ“ƒ Motivating Example

Today, the following fails type checking:

class Success<T> { constructor(readonly value: T) {} }
class Failure { constructor(error: any) {} }
type Result<T> = Success<T> | Failure;

const result: Result<string> = new Success("example");

switch (result.constructor) {
  case Success:
    console.log(`Success: ${result.value}`);
    break;
  case Failure:
    console.log(`Failure: ${result.error}`);
    break;
}

πŸ’» Use Cases

Ad-hoc polymorphism.

Many people think this already works.

Request (2018) redirected to a (completed, but different) issue: #2214 (comment)

Blog post (2020) claiming this feature exists: https://log.havrlant.cz/typescript-switch-instanceof/ (Sadly, the author's demonstration was flawed.)

if can work instead, but gives up the performance advantages of switch for a lot of branches.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions