出现错误:对于扩展 A 的类 B,类型“typeof B”无法分配给类型“typeof A”

Bru*_*res 4 javascript inheritance typeof typescript

此处可重现的示例

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

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

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

和一个类层次结构如下:

// 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
}
Run Code Online (Sandbox Code Playgroud)

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

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

方法调用为:

const result = await this.getContent.execute({
  contentType: PublicContent,
  contentPropsType: PublicContentProps,
});
Run Code Online (Sandbox Code Playgroud)

我的问题是:为什么我会在PublicContent扩展时收到此错误Content

编辑:Entity根据@Chase的要求,和的完整类型EntityProps

// 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

jca*_*alz 8

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

class Foo {
  x = 1;
  constructor() { }
  static z = 3;
}

class Bar extends Foo {
  y: string;
  constructor(y: number) {
    super()
    this.y = y.toFixed(1);
  }
}
Run Code Online (Sandbox Code Playgroud)

这里,class Bar extends Foo意味着如果你有一个 type 的值Bar,你可以将它分配给一个 type 的变量Foo

const bar: Bar = new Bar(2);
const foo: Foo = bar; // okay
Run Code Online (Sandbox Code Playgroud)

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

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

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

const oopsAtRuntime = new fooCtor(); // TypeError: y is undefined
Run Code Online (Sandbox Code Playgroud)

出于同样的原因,您的PublicContent构造函数不能分配给typeof Content. 前者需要类型的构造签名参数PublicContentProps,而后者将接受扩展类型的任何参数ContentPropsPublicContent如果您尝试像构造函数一样使用它Content,则可能会向其传递除 之外的某种类型的参数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 */ };
Run Code Online (Sandbox Code Playgroud)

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

const entity = getContent({
  contentType: PublicContent,
  contentPropsType: PublicContentProps,
}); // okay
Run Code Online (Sandbox Code Playgroud)

Playground 代码链接