Skip to content
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

Type narrow with switch(obj.constructor) #54404

Closed
5 tasks done
pauldraper opened this issue May 26, 2023 · 2 comments
Closed
5 tasks done

Type narrow with switch(obj.constructor) #54404

pauldraper opened this issue May 26, 2023 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@pauldraper
Copy link

pauldraper commented May 26, 2023

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.

@fatcerberus
Copy link

fatcerberus commented May 26, 2023

Duplicate of #16035.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label May 26, 2023
@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