Skip to content

Make instanceof operator infer default generic typesΒ #48438

Closed
@mkol

Description

@mkol

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions