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
Currently, we can only narrow object by constructor using instanceof or is, but when there are many conditions, that's inefficient.
instanceof
is
if ( object instanceof ClassA ) { object.methodOnClassA(); } else if ( object instanceof ClassB ) { object.methodOnClassB(); } else if ( object instanceof ClassC ) { object.methodOnClassC(); } else if ( object instanceof ClassD ) { object.methodOnClassD(); }
function isClassA (object) :object is ClassA { return ( object.constructor===ClassA ) as any; } if ( isClassA(object) ) { object.methodOnClassA(); }
switch ( object.constructor ) { case ClassA: object.methodOnClassA(); break; case ClassB: object.methodOnClassB(); break; case ClassC: object.methodOnClassC(); break; case ClassD: object.methodOnClassD(); break; }
BTW: .constructor=== is already supported, so I think the problem is about switch.
.constructor===
switch
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered:
Duplicate #16035
In general this isn't a good pattern to use because it doesn't allow for subclasses of these types to be correctly detected
Sorry, something went wrong.
No branches or pull requests
Search Terms
constructor
Suggestion
Use Cases
Currently, we can only narrow object by constructor using
instanceof
oris
, but when there are many conditions, that's inefficient.Examples
BTW:
.constructor===
is already supported, so I think the problem is aboutswitch
.Checklist
My suggestion meets these guidelines:
The text was updated successfully, but these errors were encountered: