【问题标题】:Getting error: Type 'typeof B' is not assignable to type 'typeof A' for class B that extends A出现错误:类型“typeof B”不可分配给扩展 A 的类 B 的类型“typeof A”
【发布时间】:2021-05-15 11:58:54
【问题描述】:

可复现的例子here

我的需要是:contentType 参数应该接受从 Content 扩展的任何类对象(PublicContent、AdminContent、PrivateContent 等),并且我想在 execute 方法内从该参数类型调用静态方法。

我有一个带有以下签名的方法:

async execute<U extends ContentProps>(input: {
    contentType: typeof Content;
    contentPropsType: typeof ContentProps; 
}): Promise<Result<U, Failure>>;

类层次结构如下:

// content.entity.ts

export class ContentProps extends EntityProps {}

export class Content<T extends ContentProps> extends Entity<T> {
  public constructor(props: T) {
    super(props);
  }
}

// public-content.entity.ts
export class PublicContentProps extends ContentProps {
  readonly title: string;
  readonly text: string;
}

export class PublicContent extends Content<PublicContentProps> {
  constructor(props: PublicContentProps) {
    super(props);
  }
  // ommited
}

问题是,当我调用 execute 方法并将 PublicContent 作为 contentType 参数传递时,我收到一条错误消息

类型“typeof PublicContent”不可分配给类型“typeof Content”

方法调用为:

const result = await this.getContent.execute({
  contentType: PublicContent,
  contentPropsType: PublicContentProps,
});

我的问题是:为什么我收到此错误,因为 PublicContent 正在扩展 Content

编辑:应@Chase 的要求,EntityEntityProps 的完整类型:

// entity.ts
export abstract class EntityProps extends BaseEntityProps {
  id?: string;
  createdAt?: Date;
  updatedAt?: Date;
}

export abstract class Entity<T extends EntityProps> extends BaseEntity<T> {
  get id(): string {
    return this.props.id;
  }

  get createdAt(): Date {
    return this.props.createdAt;
  }

  get updatedAt(): Date {
    return this.props.updatedAt;
  }

  protected constructor(entityProps: T) {
    super(entityProps);
  }
}


// base.entity.ts
export abstract class BaseEntityProps {}

export abstract class BaseEntity<T extends BaseEntityProps> extends Equatable {
  protected readonly props: T;

  protected constructor(baseEntityProps: T) {
    super();
    this.props = baseEntityProps;
  }

  static create<T = BaseEntity<BaseEntityProps>, U = BaseEntityProps>(
    this: {
      new (entityProps: U): T;
    },
    propsType: { new (): U },
    props: U,
  ): Result<T, ValidationFailure> {
    const violations = validateSchemaSync(propsType, props);

    return violations?.length
      ? Result.fail(new ValidationFailure(violations))
      : Result.ok(new this({ ...props }));
  }

  toJSON(): T {
    return this.props;
  }
}

【问题讨论】:

  • 为什么是typeoftypeof Content 为您提供类对象的类型(静态端),而 Content 是实例端类型。所以应该不兼容。如果要引用实例端(从类实例化的对象)- 删除 typeofs
  • @Chase 这是因为我在 execute 方法中使用了来自 *Contentstatic 方法。基本上,我的需要是:contentType 参数应该接受从Content 扩展的任何类对象(PublicContentAdminContentPrivateContent 等)
  • 啊,我明白了。您可以发布EntityPropsEntity 的完整类型吗?以及完整的错误——通常错误会抱怨特定的不兼容——在这种情况下,它应该告诉你一些类似于“构造函数签名不兼容”的内容
  • 请考虑修改您的示例代码以构成一个适合放入独立 IDE 的 minimal reproducible example,例如 The TypeScript Playground,它展示了您所面临的问题,并且仅展示了您所面临的问题。理想情况下,这意味着您将删除与问题无关的任何内容。这样一来,想要帮助您解决问题的人就可以着手解决问题,而无需首先努力解决问题……并且增加了答案适用的机会。
  • 嗨@jcalz 感谢您的评论。 Here 一个可重现的例子。感谢您的帮助!

标签: javascript typescript inheritance typeof


【解决方案1】:

尝试让Content实现一个简单的接口,比如IContent,并使用这个接口来获取execute参数上的typeof

【讨论】:

    【解决方案2】:

    您遇到的问题是超类/子类构造函数 并不总是形成类型层次结构,即使它们的实例 确实如此。我们来看一个例子:

    class Foo {
      x = 1;
      constructor() { }
      static z = 3;
    }
    
    class Bar extends Foo {
      y: string;
      constructor(y: number) {
        super()
        this.y = y.toFixed(1);
      }
    }
    

    这里,class Bar extends Foo 表示如果你有一个Bar 类型的值,你可以将它分配给一个Foo 类型的变量:

    const bar: Bar = new Bar(2);
    const foo: Foo = bar; // okay
    

    但是,如果您尝试将Bar 构造函数typeof Bar 类型)分配给与Foo 构造函数(typeof Foo 类型)相同类型的值,它失败:

    const fooCtor: typeof Foo = Bar; // error!
    // Type 'new (y: number) => Bar' is not assignable to type 'new () => Foo'
    

    这是因为Bar 构造函数在调用其构造签名时需要number 类型的参数(即new Bar(2)),而Foo 构造函数根本不带任何参数(即new Foo()) .如果您尝试将Bar 当作Foo 构造函数一样使用,并且不带参数调用它,您将收到运行时错误:

    const oopsAtRuntime = new fooCtor(); // TypeError: y is undefined
    

    出于同样的原因,您的PublicContent 构造函数不能分配给typeof Content。前者需要PublicContentProps 类型的构造签名参数,而后者将接受扩展ContentProps 类型的任何参数。如果您尝试像使用 Content 构造函数一样使用 PublicContent,则可能会向其传递 PublicContentProps 以外的其他类型的参数,这可能会导致错误。


    所以让我们退后一步。事实上,您并不关心您作为contentType 传递的对象是否可分配给Content 构造函数类型,因为您不会使用任意ContentProps 调用它的构造签名。你真的只关心它的静态create() 方法的类型。我倾向于将getContent() 写成这样的通用函数:

    const getContent = <U extends ContentProps, T extends BaseEntity<U>>(input: {
      contentType: Pick<typeof Content, "create"> & (new (entityProps: U) => T);
      contentPropsType: new () => U;
    }): U => { /* impl */ };
    

    这应该与函数内部的现有版本类似,现在您可以毫无错误地调用它,因为PublicContent 匹配Contentcreate 方法,并且是类型的构造函数(new (entityProps: PublicContentProps) =&gt; PublicContent):

    const entity = getContent({
      contentType: PublicContent,
      contentPropsType: PublicContentProps,
    }); // okay
    

    Playground link to code

    【讨论】:

    • 太棒了!这正是我解决问题所需要的。很好的解释!非常感谢!
    最近更新 更多