Extend Interfaces with logic in TypeScript?

Advertisements

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

>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.

Leave a ReplyCancel reply