kreedz
kreedz

Reputation: 1

What is the difference between interfaces with function properties like "f()" and "f: () =>"?

Consider next A and B interfaces:

interface A {f(): number}
interface B {f: () => number}

I've tried next things:

var a: A = {f: function() {return 1}}
var a: A = {f: () => 1}
var b: B = {f: function() {return 1}}
var b: B = {f: () => 1}

Looks like the same.

Upvotes: 0

Views: 54

Answers (2)

Nitzan Tomer
Nitzan Tomer

Reputation: 164147

This:

interface A { f(): number }

Is the notation for declaring a method, and this:

interface B { f: () => number }

Is how to declare a property of a function type.

While there's no real difference when it comes to interfaces it makes more sense in a class:

class MyClass {
    fn1() {
        return 0;
    }

    fn2 = () => {
        return 0;
    }

    fn3 = function () {
        return 0;
    }
}

Compiles to:

var MyClass = (function () {
    function MyClass() {
        this.fn2 = function () {
            return 0;
        };
        this.fn3 = function () {
            return 0;
        };
    }
    MyClass.prototype.fn1 = function () {
        return 0;
    };
    return MyClass;
}());

As you can see only fn1 is a method attached to the prototype, while the other two are just properties (assigned in the constructor).

Upvotes: 1

Duncan Lukkenaer
Duncan Lukkenaer

Reputation: 13944

They are the same. They are just two different notations. Your interfaces say that there must be a property f, which is a function with no parameters returning a number.

{f: function() {return 1}} and {f: () => 1} are two ways to implement this interface. The only difference is that the second one makes use of an arrow function. This is mostly syntatic sugar, but differs slightly by the use of the this keyword.

Upvotes: 2

Related Questions