Skip to content

Make instanceof operator infer default generic types #48438

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
mkol opened this issue Mar 26, 2022 · 2 comments
Closed

Make instanceof operator infer default generic types #48438

mkol opened this issue Mar 26, 2022 · 2 comments

Comments

@mkol
Copy link

mkol commented Mar 26, 2022

Suggestion

Make instanceof operator infer default generic types.

πŸ” Search Terms

instanceof, generic

βœ… Viability Checklist

My suggestion meets these guidelines:

  • [ x ] This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • [ x ] This wouldn't change the runtime behavior of existing JavaScript code
  • [ x ] This could be implemented without emitting different JS based on the types of the expressions
  • [ x ] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • [ x ] This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

The instanceof operator used for generics, should narrow the template type to its default.

class Id {
  value = 0;
}
class Box<T extends Id = Id> {
  constructor(public id: T) {}
}

function getId(obj: unknown): number {
  if (obj instanceof Box) {
    return obj.id.value; // here obj is Box<any> => obj.id is any => obj.id.value is any
  }
  return -1;
}

W/o this, there is an awkward workaround: instead of using obj instanceof Box one can use isBox(obj)

function isBox(obj: unknown): obj is Box {
  return obj instanceof Box;
}

which is just a "typed" version obj instanceof Box... This approach works, but with multiple (especially nested) generic classes, doesn't scale well...

πŸ’» Use Cases

  • reference/usage tracking
  • conformance with @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-return, and similar any-related recommended rules
  • refactoring: w/o proper typing, in the example above, renaming value within Id will not result in a change in obj.id.value
@MartinJohns
Copy link
Contributor

MartinJohns commented Mar 26, 2022

Related: #17473 - That issue is about inferring the constraint (which IMO makes more sense), while yours is about inferring the default.

Inferring the constraint makes more sense, because the default type can be more specific.

function test<T extends string = 'a'>() {}

@mkol
Copy link
Author

mkol commented Mar 26, 2022

From my perspective this is actually a duplicate of #17473.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants