通用类型兼容性问题

时间:2018-02-06 13:25:25

标签: typescript

使用此代码,我在m1和m2处获得语法错误,基本上说:Type 'T' is not assignable to Type 'boolean'Type 'T' is not assignable to Type 'string'

interface myMethod {
    <T>(b: T): myObject<T>;
}


class myObject<T> {

    constructor(private gg: T) {
    }

}

var m1: myMethod = function (b : boolean) {

    return new myObject(b);
}

var m2: myMethod = function (b: string) {

    return new myObject(b);
}

我该怎么办?

1 个答案:

答案 0 :(得分:1)

myMethod定义的签名是通用的,因此只有通用函数才能满足签名,或者用T替换var m1: myMethod = function <T>(b : T) { return new myObject(b); } // Works but I would not recommend id. var m2: myMethod = function (b : any) { return new myObject(b); } 的签名。

enquo/!!