Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 800
Opat Avatar asked Jan 19 '26 00:01

Opat


1 Answers

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.

like image 65
mbdavis Avatar answered Jan 21 '26 13:01

mbdavis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!