从typescript接口实现泛型方法

时间:2017-12-02 12:15:58

标签: typescript generics

我正在尝试将typescript泛型与继承结合使用,但我无法理解为什么下面的代码会导致错误

interface One {
    // something here
}

interface Two extends One {
    method<T extends One>(val: T): void;
}

class Three implements Two {
    method(val: Three): void {
        // do something with val
    }
}

是否有任何线索导致错误以及如何以正确的方式实施错误?

1 个答案:

答案 0 :(得分:0)

如果接口定义了泛型方法,则实现也必须是通用的

"slug": "compute",
"displayName": "Compute",
"products": [{
    "slug": "virtual-machines",
    "displayName": "Virtual Machines",
    "description": "Provision Windows and Linux virtual machines in seconds",
    "keywords": "series,sql server,biztalk,instances,vm,ri,paygo,ec2,gpu,cpu,vms,sharepoint,reserved instances,nvidia",
    "pricingUrl": "/pricing/details/virtual-machines/"
},
{...}

如果希望接口实现一个以当前类型为参数的函数,可以使用class Three implements Two { method<T extends One>(val: T): void { // do something with val } } 类型:

this