Closed
Description
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 similarany
-related recommended rules - refactoring: w/o proper typing, in the example above, renaming
value
withinId
will not result in a change inobj.id.value
Metadata
Metadata
Assignees
Labels
No labels