首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >指定子类中基类的静态方法的错误

指定子类中基类的静态方法的错误
EN

Stack Overflow用户
提问于 2022-09-15 12:54:00
回答 1查看 27关注 0票数 1

下面是我正在做的一个简单的例子:

代码语言:javascript
运行
复制
enum Type {A, B}

class Base<T extends Type> {
  constructor(public type: T) {}

  static create<T extends Type>(type: T): Base<T> {
    return new Base(type);
  }
}

class A extends Base<Type.A> {
  static override create(): A {
    return super.create(Type.A);
  }
}

但我发现了一个错误:

代码语言:javascript
运行
复制
Class static side 'typeof A' incorrectly extends base class static side 'typeof Base'.
  The types returned by 'create(...)' are incompatible between these types.
    Type 'A' is not assignable to type 'Base<T>'.
      Type 'Type.A' is not assignable to type 'T'.
        'Type.A' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Type'. ts(2417)

为什么会这样呢?当我显式地从'T' could be instantiated with a different subtype of constraint 'Type'扩展时,我不明白“Base<Type.A>”是怎么回事。如何在此基础上创建基类的专门化?

EN

回答 1

Stack Overflow用户

发布于 2022-09-15 14:31:19

我们在此有几个问题:

  1. 您使用的是,而不是子类中的类型

javascript class Base<T extends Type>意味着您必须提供扩展类型的T。但是您提供了一个值javascript class A extends Base<Type.A>

value/instance.泛型中,只能提供类型的,而不能提供类型的。示例:

代码语言:javascript
运行
复制
class Animal {}
class Cat extends Animal {}

class AnimalInfo<T extends Animal> {}

const catInfo = new AnimalInfo<Cat>(); //valid - we provide type

const catInstane = new Cat();
const anotherCatInfo = new AnimalInfo<catInstane>(); // not valid

一个有效的,虽然不是非常有用的例子是:

代码语言:javascript
运行
复制
enum Type {
  A,
  B,
}

enum AnotherType {
  C,
}

type CombinedEnum = Type & AnotherType;

class Base<T extends Type> {
  constructor(public type: T) {}

  static create<T extends Type>(type: T): Base<T> {
    return new Base(type);
  }
}

class A extends Base<CombinedEnum> {
}

  1. Static方法不能被重写的。只有overridden

方法可以是实例方法

javascript static override create() ...不是一个有效的结构。

  1. super在静态方法中没有任何意义。超级应用于实例,而不是静态类

代码语言:javascript
运行
复制
  static method(): Something {
    return super.method();
  }

一个有效的结构是:

代码语言:javascript
运行
复制
class BaseClassType {
  static method(): Something {
   //...
  }
}

class AnotherClass {
  static method(): Something {
    return BaseClassType.method();
  }
}
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73731523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档