Error casting a generic type to a concrete one

时光怂恿深爱的人放手 提交于 2020-02-01 10:07:31

问题


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?


回答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.



来源:https://stackoverflow.com/questions/18735178/error-casting-a-generic-type-to-a-concrete-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!