Opat
Opat

Reputation: 133

How to define a function in an interface in Angular?

I have the following problem for which I did not find a working solution. I have an interface in my Angular Application:

export interface Person {
    forename: string;
    surname: string;
}

How would I have to define a function named getFullName() with following implementation:

getFullName(){
  return this.forename + " " + this.surname;
}

I tried it directly in the interface with the function as key but it did not work...

Upvotes: 3

Views: 15640

Answers (1)

mbdavis
mbdavis

Reputation: 4010

You can use the function signature () => string to represent a function which takes 0 arguments and returns a string.

export interface Person {
    forename: string;
    surname: string;
    getFullName: () => string;
}

You can't define the implementation in the interface though.

To create a class that implements the interface you can do the following:

class MyPerson implements Person {
  constructor(public forename: string, public surname: string) { }
 
  getFullName() {
    return this.forename + " " + this.surname;
  } 
}

You possibly don't need the interface Person in this case - instead you could just use the class.

Upvotes: 9

Related Questions