Home > Net >  How to extend only the type declarations from another class?
How to extend only the type declarations from another class?

Time:09-13

If we have 2 different classes A and B that share 77 property-type declarations, but not the methods (including the constructor):

class A {
 public p1:number
 public p2: string
 //...
 public p77:"hello";
 constructor(){
 this.p1 = 5
 //...
 }
}

class B {
 public p1:number;
 public p2:string;
 //...
 public p77:"hello";
 public p78: number
//... more properties
 constructor(){
// they set properties in a different way
this.p1=879;
//...
this.p78=8;
 }
}

Is there any way to use the first 77 properties type declarations from class A in class B? Is there any way for B to extend A type declaration?

I searched everywhere and couldn't come up with a solution.

How can I avoid declaring properties twice here?

CodePudding user response:

Create a base class and then extend from it.

Something similar to this:

class BaseClass {
  public p1: string
  public p2: string
  public p3: string

  constructor() {
    this.p1 = ""
    this.p2 = ""
    this.p3 = ""
  }
}

class A extends BaseClass {
  constructor() {
    super()
    this.p1 = "a"
    this.p2 = "a"
    this.p3 = "a"
  }
}

class B extends BaseClass {
  constructor() {
    super()
    this.p1 = "b"
    this.p2 = "b"
    this.p3 = "b"
  }
}

const a = new A()
const b = new B()

Playground here.

CodePudding user response:

I see difference with p77 property, is it intentional, or a typo?

Looks like you can solve your problem with inheritance.

class SharedAncestorForAnB {
    public p1:number;
    public p2: string;
    // more props
}

class A extends SharedAncestorForAnB {
    // class' own stuff here, if any
}

class B extends SharedAncestorForAnB {
    // class' own stuff here
}
  • Related