I have the following TypeScript function:
add(element: T) {
if (element instanceof class1) (<class1>element).owner = 100;
}
the problem is that I'm getting the following error:
error TS2012: Cannot convert 'T' to 'class1'
Any ideas?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With