简体   繁体   English

Typescript class 吸气剂未返回任何数据

[英]Typescript class getters are not returning any data

I am trying to create a Typescript class that has read-only properties based on other properties in the class. The properties in question are the firstLastName and lastFirstName properties.我正在尝试创建一个 Typescript class,它具有基于 class 中其他属性的只读属性。所讨论的属性是 firstLastName 和 lastFirstName 属性。 Here is my class:这是我的 class:

export interface IMember {
  id: string;
  firstName: string;
  lastName: string;
  active: boolean;
  readonly firstLastName: string;
  readonly lastFirstName: string;
}

export class Member implements IMember {
  id: string;
  firstName: string;
  lastName: string;
  active: boolean;
  get firstLastName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
  get lastFirstName(): string {
    return `${this.lastName}, ${this.firstName}`;
  }
}

I have tried manually creating a new member object and assigning the four required properties, and I also tried creating member objects from JSON. In both cases, the code acts like the firstLastName and lastFirstName properties aren't there at all.我已经尝试手动创建一个新成员 object 并分配四个必需的属性,我还尝试从 JSON 创建成员对象。在这两种情况下,代码的行为就像 firstLastName 和 lastFirstName 属性根本不存在一样。 Also, when creating the object manually, I have to mark the type as Partial, or the compiler complains that the object is missing properties (firstLastName and lastFirstName).此外,在手动创建 object 时,我必须将类型标记为部分类型,否则编译器会抱怨 object 缺少属性(firstLastName 和 lastFirstName)。 This seems so straightforward, and I found another question here that basically showed exactly what I'm doing as the solution, but it's just not working for me.这看起来很简单,我在这里发现了另一个问题,它基本上准确地显示了我正在做的解决方案,但它对我不起作用。

Mb You have to initialize properties. Mb 您必须初始化属性。 This code works in the playground:此代码在操场上有效:

interface IMember {
  id: string;
  firstName: string;
  lastName: string;
  active: boolean;
  readonly firstLastName: string;
  readonly lastFirstName: string;
}

class Member implements IMember {
  id: string = "";
  firstName: string = "first";
  lastName: string = "last";
  active: boolean = false;
  get firstLastName(): string {
    return `${this.firstName} ${this.lastName}`;
  }
  get lastFirstName(): string {
    return `${this.lastName}, ${this.firstName}`;
  }
}

const m = new Member

console.log(m.firstLastName)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM