用TypeScript中的逻辑扩展接口?[重复]

i5desfxk  于 2023-02-13  发布在  TypeScript
关注(0)|答案(3)|浏览(134)
    • 此问题在此处已有答案**:

typescript default function inside interface(3个答案)
昨天关门了。
我有一个Interface,我想在其中创建使用其他属性的计算属性。
例如,我的Person接口有名字和姓氏属性,我如何扩展Person接口以提供一个名为fullName的新属性供所有实现者组合名字和姓氏属性?

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
oalqel3c

oalqel3c1#

对于这种情况,我将继续使用父类

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())

这是fiddle

webghufk

webghufk2#

扩展Person接口以添加fullName属性的一种方法是使用getter:

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

class Pilot implements Person {
  firstName: string;
  lastName: string;

  constructor(firstName: string, lastName: string) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  get fullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
}

class Sailor implements Person {
  firstName: string;
  lastName: string;

  constructor(firstName: string, lastName: string) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  get fullName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
}

const pilot = new Pilot("Joe", "Alpha");
const sailor = new Sailor("Jane", "Beta");

console.log(pilot.fullName); // Joe Alpha
console.log(sailor.fullName); // Jane Beta
zte4gxcn

zte4gxcn3#

我认为在TypeScript中将getter函数绑定到接口是不可能的,但是你可以使用一个父类Person来实现一个接口IPerson,来达到你想要的效果:

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

class Person implements IPerson {
  constructor(public firstName: string, public lastName: string) {}
  public get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

class Pilot extends Person {
  constructor(public firstName: string, public lastName: string) {
    super(firstName, lastName);
  }
}

class Sailer extends Person {
  constructor(public firstName: string, public lastName: string) {
    super(firstName, lastName);
  }
}

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

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

相关问题