You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
The text was updated successfully, but these errors were encountered:
Suggestion
Make
instanceof
operator infer default generic types.π Search Terms
instanceof, generic
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
The
instanceof
operator used for generics, should narrow the template type to its default.W/o this, there is an awkward workaround: instead of using
obj instanceof Box
one can useisBox(obj)
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
@typescript-eslint/no-unsafe-argument
,@typescript-eslint/no-unsafe-return
, and similarany
-related recommended rulesvalue
withinId
will not result in a change inobj.id.value
The text was updated successfully, but these errors were encountered: