[英]implementing generic method from typescript interface
我正在嘗試將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
}
}
有什么線索為什么會導致錯誤以及如何以正確的方式實現它?
如果接口定義了通用方法,則實現也必須是通用的
class Three implements Two {
method<T extends One>(val: T): void {
// do something with val
}
}
如果希望接口實現將當前類型作為參數的函數,則可以使用this
類型:
interface Two extends One {
method(val: this): void;
}
class Three implements Two {
method(val: this): void {
// do something with val
}
}
var a = new Three();
a.method(a); //OK
a.method({}); //Not OK
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.