Skip to content

use .constructor to narrow type #39067

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

Closed
5 tasks done
LongTengDao opened this issue Jun 14, 2020 · 1 comment
Closed
5 tasks done

use .constructor to narrow type #39067

LongTengDao opened this issue Jun 14, 2020 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@LongTengDao
Copy link
Contributor

LongTengDao commented Jun 14, 2020

Search Terms

constructor

Suggestion

Use Cases

Currently, we can only narrow object by constructor using instanceof or is, but when there are many conditions, that's inefficient.

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(); }

Examples

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.

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, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.
@RyanCavanaugh
Copy link
Member

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

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jun 14, 2020
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

2 participants