将一般类型转换为具体类型时出错 [英] Error casting a generic type to a concrete one

查看:87
本文介绍了将一般类型转换为具体类型时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下TypeScript函数:

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:


错误TS2012:无法将'T'转换为'class1'

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

有什么想法吗?

推荐答案

不能保证您的类型兼容,因此您必须进行双重转换,因为每个以下内容...

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;
    }
}

这是使用 class1 作为约束,但是您可能决定使用任何类都必须满足才能有效的接口-例如,它必须具有名为 owner 的属性。类型为数字

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.

这篇关于将一般类型转换为具体类型时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆