【问题标题】:Error casting a generic type to a concrete one将泛型类型转换为具体类型时出错
【发布时间】:2013-09-11 07:30:47
【问题描述】:

我有以下 TypeScript 函数:

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

问题是我收到以下错误:

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

有什么想法吗?

【问题讨论】:

    标签: typescript generics casting compiler-errors


    【解决方案1】:

    无法保证您的类型是兼容的,因此您必须按照以下方式进行双重转换...

    class class1 {
        constructor(public owner: number) {
    
        }
    }
    
    class Example<T> {
        add(element: T) {
            if (element instanceof class1) {
                 (<class1><any>element).owner = 100;
             }
        }
    }
    

    当然,如果您使用泛型类型约束,您可以移除强制转换和检查...

    class class1 {
        constructor(public owner: number) {
    
        }
    }
    
    class Example<T extends class1> {
        add(element: T) {
            element.owner = 100;
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多