Closed
Description
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.