2

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);
   }
2
  • You can't add functionality to an interface. Can you use a class instead? Commented Mar 17, 2020 at 8:17
  • Which is the correct syntax ??? Commented Mar 17, 2020 at 8:18

2 Answers 2

2

You can do it like below in type script

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

let p: PersonItem = {name:"Ankur", lastName:"shah", fullName: function(this){ return this.name + ' ' + this.lastName}};
let temp  = p.fullName();
Sign up to request clarification or add additional context in comments.

Comments

1

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"
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.