'Getter in class is always undefined

I have a typescript class which contains a getter (which is just a concatenation of multiple properties).

For some reason, the getter always returns undefined, even if the properties inside are all defined.

import { IdDisplayName } from './';

export class Person {
  id?: number;
  age!: number;
  personType!: IdDisplayName<number>;
  name!: string = '';

  public get description() : string {
    return this.name + ' • ' + (this.personType.displayName ?? 'No type')
      + '/' + this.age;
  }
}

I'm receiving the data as a Json and casting to Person like so:

let person = result as Person;
let desc = person.description; //undefined, never enters the description getter code.


Solution 1:[1]

The issue is you are casting result as person instead of instantiating a new instance of person. Here is a potential fix -

import { IdDisplayName } from './';

export class Person {
  constructor(result: 'your result type here') {
    this.id = result.id;
    this.age = result.age;
    this.personType = result.personType;
    this.name = result.name;
  }
  id?: number;
  age!: number;
  personType!: IdDisplayName<number>;
  name = '';

  public get description(): string {
    return (
      this.name +
      ' • ' +
      (this.personType.displayName ?? 'No type') +
      '/' +
      this.age
    );
  }
}

then it can be used like this -

let person = new Person(result)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TheFlorinator