【问题标题】:Extending Typescript generic class with abstract methods使用抽象方法扩展 Typescript 泛型类
【发布时间】:2019-11-07 00:49:44
【问题描述】:

我正在尝试扩展抽象泛型类,但在扩展某些方法时遇到了问题。

考虑一下:

abstract class A<T,K> {

    protected abstract upload<S>(item: T): S
    protected abstract download(item: T): K

}

class B<T, K > extends A<T, K>{

    protected upload(item: T):string {
        return 'hello'
    }
    protected download(item: T): number{
        return 1

    }

}

B 类中的 upload 方法的错误是:

Property 'upload' in type 'B<T, K>' is not assignable to the same property in base type 'A<T, K>'.
  Type '(item: T) => string' is not assignable to type '<S>(item: T) => S'.
    Type 'string' is not assignable to type 'S'.

对于download 类中的B 方法:

Property 'download' in type 'B<T, K>' is not assignable to the same property in base type 'A<T, K>'.
  Type '(item: T) => number' is not assignable to type '(item: T) => K'.
    Type 'number' is not assignable to type 'K'.
      'number' is assignable to the constraint of type 'K', but 'K' could be instantiated with a different subtype of constraint '{}'.

Typescript Playground Link

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    所以,B 类中的两个函数都包含你不能做的事情。

    我不知道你的最终代码会是什么样子,但它可能是这样的:

    abstract class A<T,K> {
    
        protected abstract upload<S>(item: T): S
        protected abstract download(item: T): K
    
    }
    
    class B<T, K > extends A<T, K>{
    
        protected upload<S>(item: T): S {
            // return something of type S
        }
    
        protected download(item: T): K {
            // return something of type K
        }
    
    }
    

    Playground Link

    你的尝试有什么问题:

    upload不能返回string,因为返回类型应该是S,这是函数的泛型参数。因为它是函数的泛型参数,它会在函数调用时指定,所以当你在类中声明它时,它仍然是泛型的,而不是特定的。所以它的签名一定是protected upload&lt;S&gt;(item: T): S

    upload 不能返回string,因为返回类型应该是K,这是 的泛型参数。因为它是类的通用参数,所以会在类实例化中指定。因此,当您定义类时,它仍然是通用的。所以它的签名一定是protected download(item: T): K

    【讨论】:

    • 那么您将如何实现这些方法?
    • 看来我无法在B 类中实现它们,因为它也是通用的?我显然做错了什么。
    • 不过,最后一段应该是“download can't return...”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多