首页 > 解决方案 > 从抽象类扩展的类中的抽象方法的键入问题

问题描述

我目前在尝试从抽象类/方法中实现 getter 时遇到问题

class Base {
  get base () {
    return "base";
  }
}



class Content1 extends Base {
  get content1 () {
    return "string";
  }
}
class Content2 extends Base {
  get content2 () {
    return 123;
  }
}



class MyBody<T extends typeof Base> {
  protected myContent : T
  constructor (inContent : T) {
    this.myContent = inContent
  }
  get content () {
    return new this.myContent() as InstanceType<T>;
  }
}



abstract class Page<T extends typeof Base> {
  protected myRoot : string
  constructor (inRoot : string) {
    this.myRoot = inRoot;
  }
  abstract get body () : MyBody<T> 
}
class Page1<T extends typeof Base> extends Page<T> {
  get body () { // <----------------- issue here
    return new MyBody(Content1);
  }
}
const p1 = new Page1("abc");
p1.body.content



class NotAbstractedPage { // <------ this is fine however
  protected myRoot : string
  constructor (inRoot : string) {
    this.myRoot = inRoot;
  }
  get body () {
    return new MyBody(Content1);
  }
}
const np = new NotAbstractedPage("abc");
np.body.content.content1;

错误是

Property 'body' in type 'Page1<T>' is not assignable to the same property in base type 'Page<T>'.
  Type 'MyBody<typeof Content1>' is not assignable to type 'MyBody<T>'.
    Type 'typeof Content1' is not assignable to type 'T'.
      'typeof Content1' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'typeof Base'.(2416)
(property) Page1<T extends typeof Base>.body: MyBody<typeof Content1>

我尝试将其转换为,typeof MyBody<T>但这只会产生更多错误。

打字稿游乐场

标签: typescripttypescript-typingstypescript-generics

解决方案


没关系,我意识到我只需要将预期的类型放入扩展部分。

原来的

class Page1<T extends typeof Base> extends Page<T> {
  get body () {
    return new MyBody(Content1);
  }
}

使固定

class Page1 extends Page<typeof Content1> {
  get body () {
    return new MyBody(Content1);
  }
}

推荐阅读