Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Difference between => and : in interface function declaration

Tags:

typescript

What is the difference between defining a function in an interface like:

interface IMyInterface1 {
    functionName(value: string): void;
}

and

interface IMyInterface2 {
    functionName: (value: string) => void;
}
like image 487
Nick Avatar asked Aug 10 '17 22:08

Nick


People also ask

How do you declare a function type in TypeScript interface?

TypeScript Interface can be used to define a function type by ensuring a function signature. We use the optional property using a question mark before the property name colon. This optional property indicates that objects belonging to the Interface may or may not have to define these properties.

Can we declare function in interface?

An interface is defined with the keyword interface and it can include properties and method declarations using a function or an arrow function.

How do you define a function in an interface?

To describe a function type with an interface, we give the interface a call signature. This is like a function declaration with only the parameter list and return type given. Each parameter in the parameter list requires both name and type.

How would you implement an interface function in TypeScript?

For example:interface myFunction { // Specify only parameters and return type: (a: string, b: Boolean, c: number): string; } const myFunc: myFunction = (x, y, z) => { return `x is ${x}, y is ${y}, z is ${z}` } // TypeScript will correctly infer "a" to be number, // "b" to be string and "c" to be boolean.


1 Answers

There's no real difference here, you can use which one you feel more comfortable with.
With that being said, I consider the first to imply a class method while the second is a member which is a function:

class MyClass1 implements IMyInterface1 {
    functionName(value: string): void {}
}

class MyClass2 implements IMyInterface2 {
    functionName = function(value: string): void {}
}

It is just a personal preference, the compiler will let you do the opposite as well:

class MyClass1 implements IMyInterface1 {
    functionName = function(value: string): void {}
}

class MyClass2 implements IMyInterface2 {
    functionName(value: string): void {}
}

In a similar way, these two notations are the same:

let obj1 = {
    functionName() {}
}

let obj2 = {
    functionName: function() {}
}

As they are both compiled to:

var obj1 = {
    functionName: function () { }
};
var obj2 = {
    functionName: function () { }
};
like image 81
Nitzan Tomer Avatar answered Oct 28 '22 08:10

Nitzan Tomer