Error casting a generic type to a concrete one
There is no guarantee that your types are compatible, so you have to double-cast, as per the following...
class class1 { constructor(public owner: number) { }}class Example<T> { add(element: T) { if (element instanceof class1) { (<class1><any>element).owner = 100; } }}
Of course, if you use generic type constraints, you could remove the cast and the check...
class class1 { constructor(public owner: number) { }}class Example<T extends class1> { add(element: T) { element.owner = 100; }}
This is using class1
as the constraint, but you might decide to use an interface that any class has to satisfy to be valid - for example it must have a property named owner
of type number
.