铸造打字稿通用的

Nat*_*isi 17 generics casting compiler-errors typescript

嗨有以下类型的脚本功能

add(element: T) {
 if (element instanceof class1) (<class1>element).owner = 100;
}
Run Code Online (Sandbox Code Playgroud)

问题我得到以下错误

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

有任何想法吗?

Fen*_*ton 34

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

class class1 {
    constructor(public owner: number) {

    }
}

class Example<T> {
    add(element: T) {
        if (element instanceof class1) {
             (<class1><any>element).owner = 100;
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

class class1 {
    constructor(public owner: number) {

    }
}

class Example<T extends class1> {
    add(element: T) {
        element.owner = 100;
    }
}
Run Code Online (Sandbox Code Playgroud)

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