Search code examples
typescriptundefinedgetter

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

  • Casting does not instantiate a class, it merely tells the compiler to treat your result like a Person class... which probably isn't the case yet.

    You have to do what you probably expected the cast to do by itself, create a constructor inside your Person class and instantiate a instance of Person with the new key-word.

    export class Person {
      constructor(res: any){
        // assign properties
      }
    }
    
    var desc = new Person(result).description;