[Fixed] Assign a value to an interface property using a function on another in angular / typescript?

Issue

I want a property value to depend on another inside the same interface in Angular 2+.
The goal is to avoid calling the same function every time I use this class inside my app.

Something like this:

  export interface PersonItem {

        _id?: number;
       name: string;
       lastName: string;
       fullName: getFullName(this.name, this.lastName)
  }

  function getFullName(name, surname) {

        return (name + ' ' + surname);
   }

Solution

You have declared an interface. Interfaces are great for declaring what properties and functions the outside world can see on an object. What they don’t do is allow you you to add any implementation detail.

The implementation detail either comes in the forms of functions or classes.

You currently have a function, but want to implement it on the object itself. For that you can create a class that implements the interface. I would recommend that you keep your interface, and pass that around where possible. The code that consumes an IPersonItem doesn’t care how fullName has been implemented, just that it exists.

export interface IPersonItem {
  _id?: number;
  name: string;
  lastName: string;
  fullName: string;
}

export class PersonItem implements IPersonItem {
  constructor(
    public name: string,
    public lastName: string,
    public _id?: number
  ) {
  }

  get fullName() { return `${this.name} ${this.lastName}`; }
}

Some example usage:

export class MyService {
  getPersonItem(): IPersonItem {
    return new PersonItem('first', 'last', 123);
  }
}

export class MyComponent {
  constructor(private myService: MyService) {}

  ngOnInit() {
    const person: IPersonItem = this.myService.getPersonItem();
    console.log(person.fullName); // "first last"
  }
}

Leave a Reply

(*) Required, Your email will not be published