Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extend Interfaces with logic in TypeScript?

I have an Interface where I’d like to create computed properties that uses other properties.

For example, my Person interface has first and last name properties. How can I extend the Person interface to provide a new property called fullName for all implementors to combine the first and last name properties?

interface Person {
  firstName: string;
  lastName: string;
}

class Pilot implements Person {
     constructor(public firstName: string, public lastName: string) {}
}

class Sailer implements Person {
     constructor(public firstName: string, public lastName: string) {}
}

const pilot = new Pilot("Joe", "Alpha")
const sailer = new Sailer("Jane", "Beta")

// Extend `Person` interface to return firstName + lastName?

console.log(pilot.fullName) // Joe Alpha
console.log(sailer.fullName) // Jane Beta

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I would go on with the parent class for this case

interface IPerson {
  firstName: string;
  lastName: string;
}

class Person implements IPerson {
  constructor(public firstName: string, public lastName: string) {}

  getFullName() {
    return this.firstName + ' ' + this.lastName;
  }
}

class Pilot extends Person {}

class Sailer extends Person {}

const pilot = new Pilot("Joe", "Alpha")
const sailer = new Sailer("Jane", "Beta")

console.log(pilot.getFullName())
console.log(sailer.getFullName())

Here is the fiddle.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading