Casting typescript generic's

2019-04-18 16:53发布

问题:

hi have the following type script function

add(element: T) {
 if (element instanceof class1) (<class1>element).owner = 100;
}

the problem i'm getting the following error

error TS2012: Cannot convert 'T' to 'class1'

any ideas?

回答1:

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.