获取错误:类型“typeof B”不可分配给扩展 A 的类 B 的类型“typeof A”

时间:2021-02-11 17:41:02

标签: javascript typescript inheritance typeof

可重现的示例 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;
  }
}

2 个答案:

答案 0 :(得分: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 constructortypeof 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 类型的参数。如果您尝试将 PublicContent 当作 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 */ };

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

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

Playground link to code

答案 1 :(得分:1)

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