Closed
Description
Would it be good to have type guarding on generic types? Or was this decided against?
Example 1
class Parent {
prop1: string;
}
class Child extends Parent {
childProp: string;
}
var t: Parent = new Child();
if (t instanceof Child) {
t.childProp; // no error
}
function myFunction<T extends Parent>(item: T) {
if (item instanceof Child) {
item.childProp; // error
}
}
I realize this example could be rewritten without generics. It's just an example :)
Example 2
Here's a scenario I came across when creating a wrapper class:
interface NedbItem {
_id: string;
}
function isNedbItem(item: any): item is NedbItem {
return item != null && typeof item._id === "string";
}
class DatabaseWrapper<T> {
getItems() {
const itemsFromDatabase: T[] = .....;
itemsFromDatabase.forEach(i => this.stripNedbID(i));
return itemsFromDatabase;
}
private stripNedbID(item: T) {
if (isNedbItem(item))
{
delete item._id; // error, _id does not exist on T
}
}
}
Maybe a generic type with no constraint should be treated like an any
type in this case? (Once type guards are fixed for any types -- See #4432)
This suggestion is probably very low on the priority scale.
I couldn't find this issue discussed elsewhere so sorry if it was.