Home > database >  Getter in class is always undefined
Getter in class is always undefined

Time:03-03

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.

CodePudding user response:

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;

CodePudding user response:

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)
  • Related