Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error casting a generic type to a concrete one

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?

like image 315
Nati Krisi Avatar asked Sep 11 '13 07:09

Nati Krisi


Video Answer


1 Answers

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.

like image 50
Fenton Avatar answered Oct 07 '22 01:10

Fenton