We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
constructor property, type narrowing
My suggestion meets these guidelines:
I would like the .constructor property to narrow the type in a switch statement.
.constructor
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; }
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.
if
switch
The text was updated successfully, but these errors were encountered:
Duplicate of #16035.
Sorry, something went wrong.
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.
No branches or pull requests
Suggestion
π Search Terms
constructor property, type narrowing
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
I would like the
.constructor
property to narrow the type in a switch statement.π Motivating Example
Today, the following fails type checking:
π» 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 ofswitch
for a lot of branches.The text was updated successfully, but these errors were encountered: