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;
}
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.
An interface is defined with the keyword interface and it can include properties and method declarations using a function or an arrow function.
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.
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.
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 () { }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With